Browse Source

Código reformatado com Black

pull/159/head
Sesostris Vieira 3 years ago
parent
commit
2329bb8ba0
  1. 542
      sigi/apps/casas/admin.py
  2. 5
      sigi/apps/casas/apps.py
  3. 61
      sigi/apps/casas/filters.py
  4. 23
      sigi/apps/casas/forms.py
  5. 43
      sigi/apps/casas/management/commands/importa_gerentes.py
  6. 312
      sigi/apps/casas/migrations/0001_initial.py
  7. 70
      sigi/apps/casas/migrations/0002_auto_20150710_1247.py
  8. 20
      sigi/apps/casas/migrations/0003_auto_20200207_0919.py
  9. 15
      sigi/apps/casas/migrations/0004_auto_20201015_0810.py
  10. 14
      sigi/apps/casas/migrations/0005_casalegislativa_gerentes_interlegis.py
  11. 6
      sigi/apps/casas/migrations/0006_remove_casalegislativa_gerente_contas.py
  12. 195
      sigi/apps/casas/migrations/0007_auto_20201016_1632.py
  13. 49
      sigi/apps/casas/migrations/0008_auto_20210218_1007.py
  14. 14
      sigi/apps/casas/migrations/0009_auto_20210406_1055.py
  15. 6
      sigi/apps/casas/migrations/0010_auto_20210406_1101.py
  16. 9
      sigi/apps/casas/migrations/0011_auto_20210406_1135.py
  17. 4
      sigi/apps/casas/migrations/0012_auto_20210406_1420.py
  18. 9
      sigi/apps/casas/migrations/0013_auto_20210406_1428.py
  19. 20
      sigi/apps/casas/migrations/0014_auto_20210406_1945.py
  20. 20
      sigi/apps/casas/migrations/0015_auto_20210407_0801.py
  21. 13
      sigi/apps/casas/migrations/0016_auto_20210407_1559.py
  22. 56
      sigi/apps/casas/migrations/0017_auto_20210416_0841.py
  23. 10
      sigi/apps/casas/migrations/0018_orgao_sigla.py
  24. 18
      sigi/apps/casas/migrations/0019_auto_20210501_1058.py
  25. 10
      sigi/apps/casas/migrations/0020_auto_20210611_0946.py
  26. 371
      sigi/apps/casas/migrations/0021_alter_orgao_options_remove_orgao_recorte_and_more.py
  27. 301
      sigi/apps/casas/models.py
  28. 15
      sigi/apps/casas/test_casas.py
  29. 9
      sigi/apps/casas/urls.py
  30. 355
      sigi/apps/casas/views.py
  31. 132
      sigi/apps/contatos/admin.py
  32. 5
      sigi/apps/contatos/apps.py
  33. 87
      sigi/apps/contatos/management/commands/importa_mesomicro.py
  34. 452
      sigi/apps/contatos/migrations/0001_initial.py
  35. 104
      sigi/apps/contatos/migrations/0002_auto_20151104_0810.py
  36. 48
      sigi/apps/contatos/migrations/0003_auto_20210416_0841.py
  37. 26
      sigi/apps/contatos/migrations/0004_auto_20210611_0946.py
  38. 290
      sigi/apps/contatos/migrations/0005_alter_mesorregiao_options_alter_microrregiao_options_and_more.py
  39. 298
      sigi/apps/contatos/models.py
  40. 279
      sigi/apps/convenios/admin.py
  41. 5
      sigi/apps/convenios/apps.py
  42. 312
      sigi/apps/convenios/migrations/0001_initial.py
  43. 13
      sigi/apps/convenios/migrations/0002_convenio_duracao.py
  44. 14
      sigi/apps/convenios/migrations/0003_auto_20210406_1945.py
  45. 114
      sigi/apps/convenios/migrations/0004_auto_20210407_1928.py
  46. 20
      sigi/apps/convenios/migrations/0005_auto_20210409_0842.py
  47. 31
      sigi/apps/convenios/migrations/0006_auto_20210416_0841.py
  48. 44
      sigi/apps/convenios/migrations/0007_auto_20210416_0918.py
  49. 42
      sigi/apps/convenios/migrations/0008_auto_20210422_1907.py
  50. 6
      sigi/apps/convenios/migrations/0009_auto_20210611_0946.py
  51. 13
      sigi/apps/convenios/migrations/0010_auto_20210819_0833.py
  52. 13
      sigi/apps/convenios/migrations/0011_convenio_data_termino_vigencia.py
  53. 8
      sigi/apps/convenios/migrations/0012_auto_20210831_0844.py
  54. 6
      sigi/apps/convenios/migrations/0013_remove_convenio_duracao.py
  55. 62
      sigi/apps/convenios/migrations/0014_gescon.py
  56. 6
      sigi/apps/convenios/migrations/0015_remove_convenio_search_text.py
  57. 21
      sigi/apps/convenios/migrations/0016_auto_20210909_0732.py
  58. 14
      sigi/apps/convenios/migrations/0017_convenio_id_contrato_gescon.py
  59. 12
      sigi/apps/convenios/migrations/0018_auto_20211208_1256.py
  60. 153
      sigi/apps/convenios/migrations/0019_alter_anexo_arquivo_alter_anexo_descricao_and_more.py
  61. 15
      sigi/apps/convenios/migrations/0020_gescon_orgaos_gestores.py
  62. 391
      sigi/apps/convenios/models.py
  63. 165
      sigi/apps/convenios/reports.py
  64. 8
      sigi/apps/convenios/urls.py
  65. 68
      sigi/apps/convenios/views.py
  66. 188
      sigi/apps/diagnosticos/admin.py
  67. 9
      sigi/apps/diagnosticos/decorators.py
  68. 156
      sigi/apps/diagnosticos/forms.py
  69. 832
      sigi/apps/diagnosticos/management/commands/ls_export.py
  70. 349
      sigi/apps/diagnosticos/migrations/0001_initial.py
  71. 15
      sigi/apps/diagnosticos/migrations/0002_auto_20160719_0920.py
  72. 15
      sigi/apps/diagnosticos/migrations/0002_auto_20170407_1024.py
  73. 14
      sigi/apps/diagnosticos/migrations/0003_auto_20201101_2240.py
  74. 12
      sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py
  75. 67
      sigi/apps/diagnosticos/migrations/0005_auto_20210416_0841.py
  76. 7
      sigi/apps/diagnosticos/migrations/0006_merge.py
  77. 153
      sigi/apps/diagnosticos/models.py
  78. 68
      sigi/apps/diagnosticos/templatetags/smart_if.py
  79. 52
      sigi/apps/diagnosticos/templatetags/test_smart_if.py
  80. 85
      sigi/apps/diagnosticos/urls.py
  81. 339
      sigi/apps/diagnosticos/views.py
  82. 43
      sigi/apps/diagnosticos/widgets.py
  83. 161
      sigi/apps/eventos/admin.py
  84. 5
      sigi/apps/eventos/apps.py
  85. 30
      sigi/apps/eventos/forms.py
  86. 298
      sigi/apps/eventos/migrations/0001_initial.py
  87. 5
      sigi/apps/eventos/migrations/0002_auto_20151016_1449.py
  88. 5
      sigi/apps/eventos/migrations/0003_auto_20151104_0810.py
  89. 5
      sigi/apps/eventos/migrations/0004_auto_20160719_0920.py
  90. 5
      sigi/apps/eventos/migrations/0004_remove_evento_curso_moodle_id.py
  91. 26
      sigi/apps/eventos/migrations/0005_auto_20210406_1945.py
  92. 72
      sigi/apps/eventos/migrations/0006_auto_20210416_0841.py
  93. 34
      sigi/apps/eventos/migrations/0007_auto_20210417_0744.py
  94. 18
      sigi/apps/eventos/migrations/0008_auto_20211104_1253.py
  95. 19
      sigi/apps/eventos/migrations/0009_tipoevento_categoria.py
  96. 110
      sigi/apps/eventos/migrations/0010_modulo.py
  97. 20
      sigi/apps/eventos/migrations/0011_auto_20211117_0633.py
  98. 12
      sigi/apps/eventos/migrations/0012_auto_20211117_0657.py
  99. 57
      sigi/apps/eventos/migrations/0013_modelodeclaracao.py
  100. 11
      sigi/apps/eventos/migrations/0014_auto_20211124_0736.py

542
sigi/apps/casas/admin.py

@ -7,8 +7,12 @@ from django_weasyprint.views import WeasyTemplateResponse
from import_export.fields import Field from import_export.fields import Field
from sigi.apps.casas.forms import OrgaoForm from sigi.apps.casas.forms import OrgaoForm
from sigi.apps.casas.models import Orgao, Presidente, Funcionario, TipoOrgao from sigi.apps.casas.models import Orgao, Presidente, Funcionario, TipoOrgao
from sigi.apps.casas.filters import (GerentesInterlegisFilter, ConvenioFilter, from sigi.apps.casas.filters import (
ExcluirConvenioFilter, ServicoFilter) GerentesInterlegisFilter,
ConvenioFilter,
ExcluirConvenioFilter,
ServicoFilter,
)
from sigi.apps.contatos.models import Telefone from sigi.apps.contatos.models import Telefone
from sigi.apps.convenios.models import Convenio from sigi.apps.convenios.models import Convenio
from sigi.apps.ocorrencias.models import Ocorrencia from sigi.apps.ocorrencias.models import Ocorrencia
@ -19,16 +23,30 @@ from sigi.apps.utils.mixins import CartExportReportMixin, LabeledResourse
class OrgaoExportResourse(LabeledResourse): class OrgaoExportResourse(LabeledResourse):
presidente = Field(column_name='presidente') presidente = Field(column_name="presidente")
telefone = Field(column_name='telefone') telefone = Field(column_name="telefone")
# servicos_seit = Field(column_name='servicos_seit') # servicos_seit = Field(column_name='servicos_seit')
contato = Field(column_name='contato') contato = Field(column_name="contato")
class Meta: class Meta:
model = Orgao model = Orgao
fields = ('municipio__codigo_ibge', 'cnpj', 'municipio__codigo_tse', fields = (
'nome', 'municipio__nome', 'municipio__uf__sigla', "municipio__codigo_ibge",
'presidente', 'logradouro', 'bairro', 'cep', 'telefone', "cnpj",
'pagina_web', 'email', 'ult_alt_endereco', 'contato') "municipio__codigo_tse",
"nome",
"municipio__nome",
"municipio__uf__sigla",
"presidente",
"logradouro",
"bairro",
"cep",
"telefone",
"pagina_web",
"email",
"ult_alt_endereco",
"contato",
)
export_order = fields export_order = fields
def dehydrate_presidente(self, orgao): def dehydrate_presidente(self, orgao):
@ -44,105 +62,189 @@ class OrgaoExportResourse(LabeledResourse):
def dehydrate_contato(self, orgao): def dehydrate_contato(self, orgao):
return ", ".join( return ", ".join(
[f"{c.cargo if c.cargo else 'Sem cargo'}: {c.nome} ({c.email})" [
f"{c.cargo if c.cargo else 'Sem cargo'}: {c.nome} ({c.email})"
for c in orgao.funcionario_set.filter(desativado=False) for c in orgao.funcionario_set.filter(desativado=False)
] ]
) )
class TelefonesInline(GenericTabularInline): class TelefonesInline(GenericTabularInline):
model = Telefone model = Telefone
readonly_fields = ('ult_alteracao',) readonly_fields = ("ult_alteracao",)
extra = 1 extra = 1
class PresidenteInline(admin.StackedInline): class PresidenteInline(admin.StackedInline):
model = Presidente model = Presidente
fields = ('nome', 'sexo', 'data_nascimento', 'nota', 'email', fields = (
'tempo_de_servico', 'ult_alteracao', 'endereco', 'municipio', "nome",
'bairro', 'cep', 'redes_sociais',) "sexo",
raw_id_fields = ('municipio',) "data_nascimento",
readonly_fields = ('ult_alteracao',) "nota",
"email",
"tempo_de_servico",
"ult_alteracao",
"endereco",
"municipio",
"bairro",
"cep",
"redes_sociais",
)
raw_id_fields = ("municipio",)
readonly_fields = ("ult_alteracao",)
extra = 1 extra = 1
max_num = 1 max_num = 1
verbose_name_plural = _('Presidente') verbose_name_plural = _("Presidente")
def get_queryset(self, request): def get_queryset(self, request):
return (self.model.objects.exclude(desativado=True) return (
.extra(select={'ult_null': 'ult_alteracao is null'}) self.model.objects.exclude(desativado=True)
.order_by('ult_null', '-ult_alteracao') .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 # 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 # campo igual a null não aparecer na frente dos mais novos
) )
class ContatoInterlegisInline(admin.StackedInline): class ContatoInterlegisInline(admin.StackedInline):
model = Funcionario model = Funcionario
fields = ('nome', 'sexo', 'data_nascimento', 'nota', 'email', 'cargo', fields = (
'funcao', 'setor', 'tempo_de_servico', 'ult_alteracao', "nome",
'endereco', 'municipio', 'bairro', 'cep', 'redes_sociais', "sexo",
'desativado', 'observacoes') "data_nascimento",
raw_id_fields = ('municipio',) "nota",
readonly_fields = ('ult_alteracao',) "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 extra = 1
inlines = (TelefonesInline,) inlines = (TelefonesInline,)
verbose_name_plural = _('Contato(s) Interlegis Vigente(s)') verbose_name_plural = _("Contato(s) Interlegis Vigente(s)")
def get_queryset(self, request): def get_queryset(self, request):
return (self.model.objects.filter(setor='contato_interlegis') return (
.extra(select={'ult_null': 'ult_alteracao is null'}).order_by( self.model.objects.filter(setor="contato_interlegis")
'-ult_alteracao') .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 extra = 0
return extra return extra
class FuncionariosInline(admin.StackedInline): class FuncionariosInline(admin.StackedInline):
model = Funcionario model = Funcionario
fields = ('nome', 'sexo', 'data_nascimento', 'nota', 'email', 'cargo', fields = (
'funcao', 'setor', 'tempo_de_servico', 'ult_alteracao', "nome",
'endereco', 'municipio', 'bairro', 'cep', 'redes_sociais', "sexo",
'desativado', 'observacoes') "data_nascimento",
raw_id_fields = ('municipio',) "nota",
readonly_fields = ('ult_alteracao',) "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 extra = 1
inlines = (TelefonesInline,) inlines = (TelefonesInline,)
verbose_name_plural = _('Outros Contatos da Casa') verbose_name_plural = _("Outros Contatos da Casa")
def get_queryset(self, request): def get_queryset(self, request):
return (self.model.objects.exclude(cargo='Presidente',) return (
.exclude(desativado=True).extra( self.model.objects.exclude(
select={'ult_null': 'ult_alteracao is null'}) cargo="Presidente",
.order_by('ult_null', '-ult_alteracao') )
.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 # 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 # o campo igual a null não aparecer na frente dos mais novos
) )
class ConveniosInline(admin.TabularInline): class ConveniosInline(admin.TabularInline):
model = Convenio model = Convenio
fieldsets = ( fieldsets = (
(None, {'fields': ( (
('link_sigad', 'status_convenio', 'num_convenio', None,
'projeto', 'observacao'), {
('data_retorno_assinatura', 'data_pub_diario',), "fields": (
('get_anexos',), (
('link_convenio',), "link_sigad",
)}), "status_convenio",
) "num_convenio",
readonly_fields = ['link_convenio', 'link_sigad', 'status_convenio', "projeto",
'num_convenio', 'projeto', 'observacao', 'data_adesao', "observacao",
'data_retorno_assinatura', 'data_termo_aceite', ),
'data_pub_diario', 'data_devolucao_via', (
'data_postagem_correio', 'data_devolucao_sem_assinatura', "data_retorno_assinatura",
'data_retorno_sem_assinatura', 'get_anexos'] "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",
]
extra = 0 extra = 0
can_delete = False can_delete = False
ordering = ('-data_retorno_assinatura',) ordering = ("-data_retorno_assinatura",)
def has_add_permission(self, request, obj): def has_add_permission(self, request, obj):
return False return False
def get_anexos(self, obj): def get_anexos(self, obj):
return mark_safe('<br/>'.join( return mark_safe(
[f'<a href="{a.arquivo.url}" target="_blank">{a}</a>' "<br/>".join(
for a in obj.anexo_set.all()]) [
f'<a href="{a.arquivo.url}" target="_blank">{a}</a>'
for a in obj.anexo_set.all()
]
)
) )
get_anexos.short_description = _('Anexos')
get_anexos.short_description = _("Anexos")
def status_convenio(self, obj): def status_convenio(self, obj):
if obj.pk is None: if obj.pk is None:
@ -159,37 +261,56 @@ class ConveniosInline(admin.TabularInline):
label = r"info" label = r"info"
return mark_safe(f'<p class="label label-{label}">{status}</p>') return mark_safe(f'<p class="label label-{label}">{status}</p>')
status_convenio.short_description = _("Status do convênio") status_convenio.short_description = _("Status do convênio")
def link_convenio(self, obj): def link_convenio(self, obj):
if obj.pk is None: if obj.pk is None:
return "" return ""
opts = self.opts opts = self.opts
url = reverse(f"admin:{opts.app_label}_{opts.model_name}_change", url = reverse(
args=[obj.pk]) f"admin:{opts.app_label}_{opts.model_name}_change", args=[obj.pk]
)
return mark_safe( return mark_safe(
f'<a href="{url}"><i class="material-icons Tiny">edit</i></a>' f'<a href="{url}"><i class="material-icons Tiny">edit</i></a>'
) )
link_convenio.short_description = _('Editar convenio')
link_convenio.short_description = _("Editar convenio")
def link_sigad(self, obj): def link_sigad(self, obj):
if obj.pk is None: if obj.pk is None:
return "" return ""
return mark_safe(obj.get_sigad_url()) return mark_safe(obj.get_sigad_url())
link_sigad.short_description = _("Processo no Senado") link_sigad.short_description = _("Processo no Senado")
class ServicoInline(admin.TabularInline): class ServicoInline(admin.TabularInline):
model = Servico model = Servico
fields = ('link_url', 'contato_tecnico', 'contato_administrativo', fields = (
'hospedagem_interlegis', 'data_ativacao', 'data_alteracao', "link_url",
'data_desativacao', 'link_servico') "contato_tecnico",
readonly_fields = ['link_url', 'contato_tecnico', 'contato_administrativo', "contato_administrativo",
'hospedagem_interlegis', 'data_ativacao', "hospedagem_interlegis",
'data_alteracao', 'data_desativacao', 'link_servico'] "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 extra = 0
max_num = 0 max_num = 0
can_delete = False can_delete = False
ordering = ('-data_alteracao',) ordering = ("-data_alteracao",)
def link_url(self, servico): def link_url(self, servico):
if servico.data_desativacao is not None: if servico.data_desativacao is not None:
@ -197,179 +318,286 @@ class ServicoInline(admin.TabularInline):
return mark_safe( return mark_safe(
f'<a href="{servico.url}" target="_blank">{servico.url}</a>' f'<a href="{servico.url}" target="_blank">{servico.url}</a>'
) )
link_url.short_description = _('URL do serviço')
link_url.short_description = _("URL do serviço")
def link_servico(self, obj): def link_servico(self, obj):
if obj.pk is None: if obj.pk is None:
return "" return ""
opts = self.opts opts = self.opts
url = reverse(f'admin:{opts.app_label}_{opts.model_name}_change', url = reverse(
args=[obj.pk]) f"admin:{opts.app_label}_{opts.model_name}_change", args=[obj.pk]
)
return mark_safe( return mark_safe(
f'<a href="{url}"><i class="material-icons Tiny">edit</i></a>' f'<a href="{url}"><i class="material-icons Tiny">edit</i></a>'
) )
link_servico.short_description = _('Editar Serviço')
link_servico.short_description = _("Editar Serviço")
def has_add_permission(self, request, obj): def has_add_permission(self, request, obj):
return False return False
class OcorrenciaInline(admin.TabularInline): class OcorrenciaInline(admin.TabularInline):
model = Ocorrencia model = Ocorrencia
fields = ('data_criacao', 'assunto', 'prioridade', 'status', fields = (
'data_modificacao', 'link_editar',) "data_criacao",
readonly_fields = ('data_criacao', 'assunto', 'prioridade', 'status', "assunto",
'data_modificacao', 'link_editar',) "prioridade",
"status",
"data_modificacao",
"link_editar",
)
readonly_fields = (
"data_criacao",
"assunto",
"prioridade",
"status",
"data_modificacao",
"link_editar",
)
extra = 0 extra = 0
max_num = 0 max_num = 0
can_delete = False can_delete = False
ordering = ('-data_modificacao',) ordering = ("-data_modificacao",)
def link_editar(self, obj): def link_editar(self, obj):
if obj.pk is None: if obj.pk is None:
return "" return ""
opts = self.opts opts = self.opts
url = reverse( url = reverse(
f'admin:{opts.app_label}_{opts.model_name}_change', f"admin:{opts.app_label}_{opts.model_name}_change", args=[obj.pk]
args=[obj.pk]
) )
return mark_safe( return mark_safe(
f'<a href="{url}"><i class="material-icons Tiny">edit</i></a>' f'<a href="{url}"><i class="material-icons Tiny">edit</i></a>'
) )
link_editar.short_description = _('Editar')
link_editar.short_description = _("Editar")
@admin.register(Orgao) @admin.register(Orgao)
class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin):
form = OrgaoForm form = OrgaoForm
resource_class = OrgaoExportResourse resource_class = OrgaoExportResourse
inlines = (TelefonesInline, PresidenteInline, ContatoInterlegisInline, inlines = (
FuncionariosInline, ConveniosInline, ServicoInline, TelefonesInline,
OcorrenciaInline,) PresidenteInline,
list_display = ('id', 'sigla', 'nome', 'get_uf', 'get_gerentes', ContatoInterlegisInline,
'get_convenios', 'get_servicos') FuncionariosInline,
list_display_links = ('sigla', 'nome',) ConveniosInline,
list_filter = ('tipo', ('gerentes_interlegis', GerentesInterlegisFilter), ServicoInline,
'municipio__uf__nome', ConvenioFilter, OcorrenciaInline,
('servico__data_desativacao', ServicoAtivoFilter), )
ExcluirConvenioFilter, ServicoFilter, list_display = (
'inclusao_digital',) "id",
ordering = ('municipio__uf__nome', 'nome') "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 queryset = queryset_ascii
fieldsets = ( fieldsets = (
(None, { (
'fields': ('tipo', 'nome', 'sigla', 'cnpj', 'gerentes_interlegis') None,
}), {
(_('Endereço'), { "fields": (
'fields': ('data_instalacao', 'logradouro', 'bairro', "tipo",
'municipio', 'cep', 'ult_alt_endereco'), "nome",
}), "sigla",
(_('Presença na Internet'), { "cnpj",
'fields': ('inclusao_digital', 'data_levantamento', 'pesquisador', "gerentes_interlegis",
'pagina_web', 'email', 'obs_pesquisa',) )
}), },
(_('Outras informações'), { ),
'fields': ('observacoes', 'horario_funcionamento', 'foto',), (
}), _("Endereço"),
) {
raw_id_fields = ('municipio',) "fields": (
readonly_fields = ['gerentes_interlegis',] "data_instalacao",
search_fields = ('search_text', 'sigla', 'cnpj', 'bairro', 'logradouro', "logradouro",
'cep', 'municipio__nome', 'municipio__uf__nome', "bairro",
'municipio__codigo_ibge', 'pagina_web', 'observacoes') "municipio",
reports = ['casas_sem_processo', 'relatorio_simples', 'relatorio_completo', "cep",
'etiqueta_presidente_25', 'etiqueta_presidente_39', "ult_alt_endereco",
'etiqueta_25', 'etiqueta_39', 'etiqueta_parlamentar_25', ),
'etiqueta_parlamentar_39',] },
),
(
_("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",
)
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): def get_queryset(self, request):
queryset = super(OrgaoAdmin, self).get_queryset(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): def get_uf(self, obj):
return obj.municipio.uf.nome 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): def get_gerentes(self, obj):
return mark_safe(obj.lista_gerentes()) return mark_safe(obj.lista_gerentes())
get_gerentes.short_description = _('Gerente Interlegis')
get_gerentes.short_description = _("Gerente Interlegis")
def get_convenios(self, obj): def get_convenios(self, obj):
return mark_safe( return mark_safe(
'<ul>' + "<ul>"
''.join([f'<li>{c}</li>' for c in obj.convenio_set.all()]) + + "".join([f"<li>{c}</li>" for c in obj.convenio_set.all()])
'</ul>' + "</ul>"
) )
get_convenios.short_description = _('Convênios')
get_convenios.short_description = _("Convênios")
def get_servicos(self, obj): def get_servicos(self, obj):
return mark_safe( return mark_safe(
'<ul>' + "<ul>"
''.join( + "".join(
[f'<li><a href="{s.url}" target="_blank">{s}</a></li>' [
f'<li><a href="{s.url}" target="_blank">{s}</a></li>'
for s in obj.servico_set.filter( for s in obj.servico_set.filter(
data_desativacao__isnull=True) data_desativacao__isnull=True
)
] ]
) +
'</ul>'
) )
get_servicos.short_description = _('Serviços') + "</ul>"
)
get_servicos.short_description = _("Serviços")
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return (super(OrgaoAdmin, self).lookup_allowed(lookup, value) or return super(OrgaoAdmin, self).lookup_allowed(
lookup in ['tipo__legislativo__exact', lookup, value
'tipo__sigla__exact', ) or lookup in [
'municipio__uf__codigo_ibge__exact', "tipo__legislativo__exact",
'convenio__projeto__id__exact']) "tipo__sigla__exact",
"municipio__uf__codigo_ibge__exact",
"convenio__projeto__id__exact",
]
def casas_sem_processo(self, request): def casas_sem_processo(self, request):
context = { context = {
'casas': self.get_queryset(request).filter(convenio=None).order_by( "casas": self.get_queryset(request)
'municipio__uf','nome'), .filter(convenio=None)
'title': _('Casas sem nenhum processo de convênio') .order_by("municipio__uf", "nome"),
"title": _("Casas sem nenhum processo de convênio"),
} }
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename='casas_sem_processo.pdf', filename="casas_sem_processo.pdf",
request=request, request=request,
template="casas/casas_sem_convenio_pdf.html", template="casas/casas_sem_convenio_pdf.html",
context=context, 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): def relatorio_simples(self, request):
context = { context = {
'casas': self.get_queryset(request).order_by( "casas": self.get_queryset(request).order_by(
'municipio__uf','nome'), "municipio__uf", "nome"
'title': _('Relatório Simples') ),
"title": _("Relatório Simples"),
} }
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename='relatorio_simples.pdf', filename="relatorio_simples.pdf",
request=request, request=request,
template="casas/casas_sem_convenio_pdf.html", template="casas/casas_sem_convenio_pdf.html",
context=context, 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): def relatorio_completo(self, request):
context = { context = {
'casas': self.get_queryset(request).order_by('municipio__uf','nome'), "casas": self.get_queryset(request).order_by(
'title': _('Relatório completo') "municipio__uf", "nome"
),
"title": _("Relatório completo"),
} }
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename='relatorio_completo.pdf', filename="relatorio_completo.pdf",
request=request, request=request,
template="casas/relatorio_completo_pdf.html", template="casas/relatorio_completo_pdf.html",
context=context, 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): def get_actions(self, request):
actions = super(OrgaoAdmin, self).get_actions(request) actions = super(OrgaoAdmin, self).get_actions(request)
if 'delete_selected' in actions: if "delete_selected" in actions:
del actions['delete_selected'] del actions["delete_selected"]
return actions return actions
admin.site.register(TipoOrgao) admin.site.register(TipoOrgao)

5
sigi/apps/casas/apps.py

@ -1,6 +1,7 @@
from django.apps import AppConfig from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class CasasConfig(AppConfig): class CasasConfig(AppConfig):
name = 'sigi.apps.casas' name = "sigi.apps.casas"
verbose_name = _('casas legislativas') verbose_name = _("casas legislativas")

61
sigi/apps/casas/filters.py

@ -8,78 +8,83 @@ from sigi.apps.servicos.models import TipoServico
class GerentesInterlegisFilter(admin.filters.RelatedFieldListFilter): class GerentesInterlegisFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
gerentes = Servidor.objects.exclude( gerentes = Servidor.objects.exclude(casas_que_gerencia=None).order_by(
casas_que_gerencia=None).order_by( "nome_completo"
'nome_completo') )
self.lookup_choices = [(x.id, x) for x in gerentes] self.lookup_choices = [(x.id, x) for x in gerentes]
class ConvenioFilter(admin.SimpleListFilter): class ConvenioFilter(admin.SimpleListFilter):
title = _("Tipo de convênio") title = _("Tipo de convênio")
parameter_name = 'convenio' parameter_name = "convenio"
def lookups(self, request, model_admin): def lookups(self, request, model_admin):
return ( return (
('SC', _("Sem nenhum convênio")), ("SC", _("Sem nenhum convênio")),
('CC', _("Com algum convênio")), ("CC", _("Com algum convênio")),
) + tuple([(p.pk, p.sigla) for p in Projeto.objects.all()]) ) + tuple([(p.pk, p.sigla) for p in Projeto.objects.all()])
def queryset(self, request, queryset): def queryset(self, request, queryset):
if self.value() is not None: if self.value() is not None:
if self.value() == 'SC': if self.value() == "SC":
queryset = queryset.filter(convenio=None) queryset = queryset.filter(convenio=None)
elif self.value() == 'CC': elif self.value() == "CC":
queryset = queryset.exclude(convenio=None) queryset = queryset.exclude(convenio=None)
else: else:
queryset = queryset.filter(convenio__projeto_id=self.value()) 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): class ExcluirConvenioFilter(admin.SimpleListFilter):
title = _("Excluir convênio da pesquisa") title = _("Excluir convênio da pesquisa")
parameter_name = 'excluir_convenio' parameter_name = "excluir_convenio"
def lookups(self, request, model_admin): def lookups(self, request, model_admin):
return tuple([(p.pk, p.sigla) for p in Projeto.objects.all()]) return tuple([(p.pk, p.sigla) for p in Projeto.objects.all()])
def queryset(self, request, queryset): def queryset(self, request, queryset):
if (self.value() is None): if self.value() is None:
return queryset return queryset
else: else:
queryset = queryset.exclude( queryset = queryset.exclude(
convenio__projeto_id=self.value()).distinct( convenio__projeto_id=self.value()
'municipio__uf__nome', 'nome') ).distinct("municipio__uf__nome", "nome")
return queryset return queryset
class ServicoFilter(admin.SimpleListFilter): class ServicoFilter(admin.SimpleListFilter):
title = _("Serviço") title = _("Serviço")
parameter_name = 'servico' parameter_name = "servico"
def lookups(self, request, model_admin): def lookups(self, request, model_admin):
return ( return (
('SS', _("Sem nenhum serviço")), ("SS", _("Sem nenhum serviço")),
('CS', _("Com algum serviço")), ("CS", _("Com algum serviço")),
('CH', _("Com algum serviço de hospedagem")), ("CH", _("Com algum serviço de hospedagem")),
('CR', _("Apenas serviço de registro")), ("CR", _("Apenas serviço de registro")),
) + tuple([(p.pk, p.nome) for p in TipoServico.objects.all()]) ) + tuple([(p.pk, p.nome) for p in TipoServico.objects.all()])
def queryset(self, request, queryset): def queryset(self, request, queryset):
if self.value() is not None: if self.value() is not None:
if self.value() == 'SS': if self.value() == "SS":
queryset = queryset.filter(servico=None) queryset = queryset.filter(servico=None)
elif self.value() == 'CS': elif self.value() == "CS":
queryset = queryset.exclude(servico=None).filter( 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 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: else:
queryset = queryset.filter( queryset = queryset.filter(
servico__tipo_servico_id=self.value() servico__tipo_servico_id=self.value()
) )
return queryset.distinct('municipio__uf__nome', 'nome') return queryset.distinct("municipio__uf__nome", "nome")

23
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.casas.models import Orgao
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
class AtualizaCasaForm(forms.Form): class AtualizaCasaForm(forms.Form):
arquivo = forms.FileField( arquivo = forms.FileField(
required=True, required=True,
@ -12,17 +13,20 @@ class AtualizaCasaForm(forms.Form):
help_text=_("Envie um arquivo no formato CSV"), help_text=_("Envie um arquivo no formato CSV"),
) )
class OrgaoForm(forms.ModelForm): class OrgaoForm(forms.ModelForm):
# cnpj = BRCNPJField( # cnpj = BRCNPJField(
# label=_('CNPJ'), # label=_('CNPJ'),
# required=False, # required=False,
# help_text=_('Utilize o formato <em>XX.XXX.XXX/XXXX-XX</em> ou insira apenas os dígitos.') # help_text=_('Utilize o formato <em>XX.XXX.XXX/XXXX-XX</em> ou insira apenas os dígitos.')
# ) # )
cep = BRZipCodeField(label=_('CEP'), help_text=_('Formato') + ': <em>XXXXX-XXX</em>.') cep = BRZipCodeField(
label=_("CEP"), help_text=_("Formato") + ": <em>XXXXX-XXX</em>."
)
class Meta: class Meta:
model = Orgao model = Orgao
fields = '__all__' fields = "__all__"
# def clean(self): # def clean(self):
# cleaned_data = super(OrgaoForm, self).clean() # cleaned_data = super(OrgaoForm, self).clean()
@ -31,23 +35,20 @@ class OrgaoForm(forms.ModelForm):
# if tipo.legislativo: # if tipo.legislativo:
# if Orgao.objects.filter(tipo=tipo) # if Orgao.objects.filter(tipo=tipo)
class PortfolioForm(forms.Form): class PortfolioForm(forms.Form):
ACAO_CHOICES = ( ACAO_CHOICES = (("ADD", _("Adicionar")), ("DEL", _("Remover")))
('ADD', _("Adicionar")),
('DEL', _("Remover"))
)
acao = forms.ChoiceField( acao = forms.ChoiceField(
label=_("Ação"), label=_("Ação"),
choices=ACAO_CHOICES, choices=ACAO_CHOICES,
initial='ADD', initial="ADD",
widget=forms.RadioSelect widget=forms.RadioSelect,
) )
gerente = forms.ModelChoiceField( gerente = forms.ModelChoiceField(
queryset=Servidor.objects.all(), queryset=Servidor.objects.all(), label=_("Atribuir para")
label=_("Atribuir para")
) )
# O label precisa ser trocado dependendo da região que se está visualizando # O label precisa ser trocado dependendo da região que se está visualizando
def __init__(self, label=_("Atribuir para"), *args, **kwargs): def __init__(self, label=_("Atribuir para"), *args, **kwargs):
super(PortfolioForm, self).__init__(*args, **kwargs) super(PortfolioForm, self).__init__(*args, **kwargs)
self.fields['gerente'].label = label self.fields["gerente"].label = label

43
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.servidores.models import Servidor
from sigi.apps.contatos.models import Municipio from sigi.apps.contatos.models import Municipio
class Command(BaseCommand): class Command(BaseCommand):
args = "data_file.csv" args = "data_file.csv"
help = """Importa dados de atribuição de gerencia de relacionamentos de um arquivo 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.""" * 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): def handle(self, *args, **options):
if len(args) != 1: if len(args) != 1:
@ -48,13 +49,20 @@ class Command(BaseCommand):
file_name = args[0] file_name = args[0]
if not os.path.isfile(file_name): if not os.path.isfile(file_name):
raise CommandError("Arquivo %s não encontrado" % [file_name,]) raise CommandError(
"Arquivo %s não encontrado"
% [
file_name,
]
)
with open(file_name, 'rb') as csvfile: with open(file_name, "rb") as csvfile:
reader = csv.DictReader(csvfile) reader = csv.DictReader(csvfile)
if not self.campos.issubset(reader.fieldnames): 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() Orgao.gerentes_interlegis.through.objects.all().delete()
@ -63,36 +71,39 @@ class Command(BaseCommand):
for reg in reader: for reg in reader:
try: try:
municipio = Municipio.objects.get( municipio = Municipio.objects.get(
codigo_ibge=reg['cod_municipio'] codigo_ibge=reg["cod_municipio"]
) )
except Municipio.DoesNotExist: except Municipio.DoesNotExist:
self.stdout.write("{linha}: não existe Município com " self.stdout.write(
"{linha}: não existe Município com "
"código IBGE {ibge}'".format( "código IBGE {ibge}'".format(
linha=reader.line_num, linha=reader.line_num, ibge=reg["cod_municipio"]
ibge=reg['cod_municipio']) )
) )
erros = erros + 1 erros = erros + 1
continue continue
try: try:
gerente = Servidor.objects.get( gerente = Servidor.objects.get(
user__username=reg['user_id'] user__username=reg["user_id"]
) )
except Servidor.DoesNotExist: except Servidor.DoesNotExist:
self.stdout.write("({linha}): não existe Servidor com " self.stdout.write(
"({linha}): não existe Servidor com "
"userid {userid}".format( "userid {userid}".format(
linha=reader.line_num, linha=reader.line_num, userid=reg["user_id"]
userid=reg['user_id']) )
) )
erros = erros + 1 erros = erros + 1
continue continue
for casa in municipio.orgao_set.filter( for casa in municipio.orgao_set.filter(
tipo__sigla__in=['AL', 'CM']): tipo__sigla__in=["AL", "CM"]
):
casa.gerentes_interlegis.add(gerente) casa.gerentes_interlegis.add(gerente)
casa.save() casa.save()
self.stdout.write("Importação concluída. {erros} erros em {linhas}" self.stdout.write(
" linhas".format(erros=erros, "Importação concluída. {erros} erros em {linhas}"
linhas=reader.line_num) " linhas".format(erros=erros, linhas=reader.line_num)
) )

312
sigi/apps/casas/migrations/0001_initial.py

@ -7,91 +7,291 @@ import sigi.apps.utils
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0001_initial'), ("servidores", "0001_initial"),
('contatos', '0001_initial'), ("contatos", "0001_initial"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='CasaLegislativa', name="CasaLegislativa",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('nome', models.CharField(help_text='Exemplo: <em>C\xc3\xa2mara Municipal de Pains</em>.', max_length=60)), "id",
('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)), models.AutoField(
('cnpj', models.CharField(max_length=32, verbose_name='CNPJ', blank=True)), verbose_name="ID",
('observacoes', models.TextField(verbose_name='observa\xe7\xf5es', blank=True)), serialize=False,
('codigo_interlegis', models.CharField(max_length=3, verbose_name='C\xc3\xb3digo Interlegis', blank=True)), auto_created=True,
('logradouro', models.CharField(help_text='Avenida, rua, pra\xc3\xa7a, jardim, parque...', max_length=100)), primary_key=True,
('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: <em>http://www.camarapains.mg.gov.br</em>.', verbose_name='p\xe1gina web', blank=True)), "nome",
('ult_alt_endereco', models.DateTimeField(null=True, verbose_name='\xdaltima altera\xe7\xe3o do endere\xe7o', blank=True)), models.CharField(
('foto', models.ImageField(height_field='foto_altura', width_field='foto_largura', upload_to='imagens/casas', blank=True)), help_text="Exemplo: <em>C\xc3\xa2mara Municipal de Pains</em>.",
('recorte', models.CharField('foto', max_length=255)), max_length=60,
('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)), "search_text",
('municipio', models.ForeignKey(verbose_name='munic\xc3\xadpio', to='contatos.Municipio', on_delete=models.CASCADE)), 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: <em>http://www.camarapains.mg.gov.br</em>.",
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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'Casa Legislativa', "verbose_name": "Casa Legislativa",
'verbose_name_plural': 'Casas Legislativas', "verbose_name_plural": "Casas Legislativas",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Funcionario', name="Funcionario",
fields=[ 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')), "id",
('sexo', models.CharField(default='M', max_length=1, choices=[('M', 'Masculino'), ('F', 'Feminino')])), models.AutoField(
('nota', models.CharField(max_length=70, null=True, blank=True)), verbose_name="ID",
('email', models.CharField(max_length=75, verbose_name='e-mail', blank=True)), serialize=False,
('cargo', models.CharField(max_length=100, null=True, blank=True)), auto_created=True,
('funcao', models.CharField(max_length=100, null=True, verbose_name='fun\xe7\xe3o', blank=True)), primary_key=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)), "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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'contato da Casa Legislativa', "verbose_name": "contato da Casa Legislativa",
'verbose_name_plural': 'contatos da Casa Legislativa', "verbose_name_plural": "contatos da Casa Legislativa",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='TipoCasaLegislativa', name="TipoCasaLegislativa",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('sigla', models.CharField(max_length=5)), "id",
('nome', models.CharField(max_length=100)), 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,), bases=(models.Model,),
), ),
migrations.AddField( migrations.AddField(
model_name='casalegislativa', model_name="casalegislativa",
name='tipo', name="tipo",
field=models.ForeignKey(verbose_name='Tipo', to='casas.TipoCasaLegislativa', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Tipo",
to="casas.TipoCasaLegislativa",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterUniqueTogether( migrations.AlterUniqueTogether(
name='casalegislativa', name="casalegislativa",
unique_together=set([('municipio', 'tipo')]), unique_together=set([("municipio", "tipo")]),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Presidente', name="Presidente",
fields=[ fields=[],
],
options={ options={
'proxy': True, "proxy": True,
}, },
bases=('casas.funcionario',), bases=("casas.funcionario",),
), ),
] ]

70
sigi/apps/casas/migrations/0002_auto_20150710_1247.py

@ -6,45 +6,75 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0001_initial'), ("servidores", "0001_initial"),
('casas', '0001_initial'), ("casas", "0001_initial"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='casalegislativa', model_name="casalegislativa",
name='data_levantamento', name="data_levantamento",
field=models.DateTimeField(null=True, verbose_name='Data/hora da pesquisa', blank=True), field=models.DateTimeField(
null=True, verbose_name="Data/hora da pesquisa", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='casalegislativa', model_name="casalegislativa",
name='inclusao_digital', 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')]), 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, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='casalegislativa', model_name="casalegislativa",
name='obs_pesquisa', name="obs_pesquisa",
field=models.TextField(verbose_name='Observa\xe7\xf5es do pesquisador', blank=True), field=models.TextField(
verbose_name="Observa\xe7\xf5es do pesquisador", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='casalegislativa', model_name="casalegislativa",
name='pesquisador', name="pesquisador",
field=models.ForeignKey(verbose_name='Pesquisador', blank=True, to='servidores.Servidor', null=True, on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Pesquisador",
blank=True,
to="servidores.Servidor",
null=True,
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='gerente_contas', 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), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='ult_alteracao', name="ult_alteracao",
field=models.DateTimeField(auto_now=True, verbose_name='\xdaltima altera\xe7\xe3o', null=True), field=models.DateTimeField(
auto_now=True,
verbose_name="\xdaltima altera\xe7\xe3o",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

20
sigi/apps/casas/migrations/0003_auto_20200207_0919.py

@ -6,20 +6,26 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0002_auto_20150710_1247'), ("casas", "0002_auto_20150710_1247"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='casalegislativa', model_name="casalegislativa",
name='horario_funcionamento', name="horario_funcionamento",
field=models.CharField(max_length=100, verbose_name='Hor\xe1rio de funcionamento da Casa Legislativa', blank=True), field=models.CharField(
max_length=100,
verbose_name="Hor\xe1rio de funcionamento da Casa Legislativa",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='data_nascimento', name="data_nascimento",
field=models.DateField(null=True, verbose_name='Data de nascimento', blank=True), field=models.DateField(
null=True, verbose_name="Data de nascimento", blank=True
),
preserve_default=True, preserve_default=True,
), ),
] ]

15
sigi/apps/casas/migrations/0004_auto_20201015_0810.py

@ -6,14 +6,21 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0003_auto_20200207_0919'), ("casas", "0003_auto_20200207_0919"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='gerente_contas', 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), 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, preserve_default=True,
), ),
] ]

14
sigi/apps/casas/migrations/0005_casalegislativa_gerentes_interlegis.py

@ -6,15 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0001_initial'), ("servidores", "0001_initial"),
('casas', '0004_auto_20201015_0810'), ("casas", "0004_auto_20201015_0810"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='casalegislativa', model_name="casalegislativa",
name='gerentes_interlegis', name="gerentes_interlegis",
field=models.ManyToManyField(related_name='casas_que_gerencia', verbose_name='Gerentes Interlegis', to='servidores.Servidor'), field=models.ManyToManyField(
related_name="casas_que_gerencia",
verbose_name="Gerentes Interlegis",
to="servidores.Servidor",
),
preserve_default=True, preserve_default=True,
), ),
] ]

6
sigi/apps/casas/migrations/0006_remove_casalegislativa_gerente_contas.py

@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0005_casalegislativa_gerentes_interlegis'), ("casas", "0005_casalegislativa_gerentes_interlegis"),
] ]
operations = [ operations = [
migrations.RemoveField( migrations.RemoveField(
model_name='casalegislativa', model_name="casalegislativa",
name='gerente_contas', name="gerente_contas",
), ),
] ]

195
sigi/apps/casas/migrations/0007_auto_20201016_1632.py

@ -6,122 +6,201 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0006_remove_casalegislativa_gerente_contas'), ("casas", "0006_remove_casalegislativa_gerente_contas"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='desativado', name="desativado",
field=models.BooleanField(default=False, verbose_name='Desativado'), field=models.BooleanField(default=False, verbose_name="Desativado"),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='observacoes', name="observacoes",
field=models.TextField(verbose_name='Observa\xe7\xf5es', blank=True), field=models.TextField(
verbose_name="Observa\xe7\xf5es", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='bairro', name="bairro",
field=models.CharField(max_length=100, verbose_name='Bairro', blank=True), field=models.CharField(
max_length=100, verbose_name="Bairro", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='cep', name="cep",
field=models.CharField(max_length=32, verbose_name='CEP'), field=models.CharField(max_length=32, verbose_name="CEP"),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='codigo_interlegis', name="codigo_interlegis",
field=models.CharField(max_length=3, verbose_name='C\xf3digo Interlegis', blank=True), field=models.CharField(
max_length=3, verbose_name="C\xf3digo Interlegis", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='email', name="email",
field=models.EmailField(max_length=128, verbose_name='E-mail', blank=True), field=models.EmailField(
max_length=128, verbose_name="E-mail", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='foto', name="foto",
field=models.ImageField(upload_to='imagens/casas', width_field='foto_largura', height_field='foto_altura', blank=True, verbose_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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='inclusao_digital', 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')]), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='logradouro', name="logradouro",
field=models.CharField(help_text='Avenida, rua, pra\xe7a, jardim, parque...', max_length=100, verbose_name='Logradouro'), field=models.CharField(
help_text="Avenida, rua, pra\xe7a, jardim, parque...",
max_length=100,
verbose_name="Logradouro",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='municipio', name="municipio",
field=models.ForeignKey(verbose_name='Munic\xedpio', to='contatos.Municipio', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Munic\xedpio",
to="contatos.Municipio",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='nome', name="nome",
field=models.CharField(help_text='Exemplo: <em>C\xe2mara Municipal de Pains</em>.', max_length=60, verbose_name='Nome'), field=models.CharField(
help_text="Exemplo: <em>C\xe2mara Municipal de Pains</em>.",
max_length=60,
verbose_name="Nome",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='casalegislativa', model_name="casalegislativa",
name='pagina_web', name="pagina_web",
field=models.URLField(help_text='Exemplo: <em>http://www.camarapains.mg.gov.br</em>.', verbose_name='P\xe1gina web', blank=True), field=models.URLField(
help_text="Exemplo: <em>http://www.camarapains.mg.gov.br</em>.",
verbose_name="P\xe1gina web",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='cargo', name="cargo",
field=models.CharField(max_length=100, null=True, verbose_name='Cargo', blank=True), field=models.CharField(
max_length=100, null=True, verbose_name="Cargo", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='nota', name="nota",
field=models.CharField(max_length=70, null=True, verbose_name='Telefones', blank=True), field=models.CharField(
max_length=70, null=True, verbose_name="Telefones", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='setor', 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')]), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='sexo', name="sexo",
field=models.CharField(default='M', max_length=1, verbose_name='Sexo', choices=[('M', 'Masculino'), ('F', 'Feminino')]), field=models.CharField(
default="M",
max_length=1,
verbose_name="Sexo",
choices=[("M", "Masculino"), ("F", "Feminino")],
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='tempo_de_servico', name="tempo_de_servico",
field=models.CharField(max_length=50, null=True, verbose_name='Tempo de servi\xe7o', blank=True), field=models.CharField(
max_length=50,
null=True,
verbose_name="Tempo de servi\xe7o",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='tipocasalegislativa', model_name="tipocasalegislativa",
name='nome', name="nome",
field=models.CharField(max_length=100, verbose_name='Nome'), field=models.CharField(max_length=100, verbose_name="Nome"),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='tipocasalegislativa', model_name="tipocasalegislativa",
name='sigla', name="sigla",
field=models.CharField(max_length=5, verbose_name='Sigla'), field=models.CharField(max_length=5, verbose_name="Sigla"),
preserve_default=True, preserve_default=True,
), ),
] ]

49
sigi/apps/casas/migrations/0008_auto_20210218_1007.py

@ -6,39 +6,54 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('contatos', '0002_auto_20151104_0810'), ("contatos", "0002_auto_20151104_0810"),
('casas', '0007_auto_20201016_1632'), ("casas", "0007_auto_20201016_1632"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='bairro', name="bairro",
field=models.CharField(max_length=100, verbose_name='Bairro', blank=True), field=models.CharField(
max_length=100, verbose_name="Bairro", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='cep', name="cep",
field=models.CharField(max_length=10, verbose_name='CEP', blank=True), field=models.CharField(
max_length=10, verbose_name="CEP", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='endereco', name="endereco",
field=models.CharField(max_length=100, verbose_name='Endere\xe7o', blank=True), field=models.CharField(
max_length=100, verbose_name="Endere\xe7o", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='municipio', name="municipio",
field=models.ForeignKey(verbose_name='Municipio', to='contatos.Municipio', null=True, on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Municipio",
to="contatos.Municipio",
null=True,
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='funcionario', model_name="funcionario",
name='redes_sociais', name="redes_sociais",
field=models.TextField(help_text='Colocar um por linha', verbose_name='Redes sociais', blank=True), field=models.TextField(
help_text="Colocar um por linha",
verbose_name="Redes sociais",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

14
sigi/apps/casas/migrations/0009_auto_20210406_1055.py

@ -6,14 +6,20 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0008_auto_20210218_1007'), ("casas", "0008_auto_20210218_1007"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='municipio', name="municipio",
field=models.ForeignKey(verbose_name='Municipio', blank=True, to='contatos.Municipio', null=True, on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Municipio",
blank=True,
to="contatos.Municipio",
null=True,
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
] ]

6
sigi/apps/casas/migrations/0010_auto_20210406_1101.py

@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0009_auto_20210406_1055'), ("casas", "0009_auto_20210406_1055"),
] ]
operations = [ operations = [
migrations.RenameModel( migrations.RenameModel(
old_name='TipoCasaLegislativa', old_name="TipoCasaLegislativa",
new_name='TipoOrgao', new_name="TipoOrgao",
), ),
] ]

9
sigi/apps/casas/migrations/0011_auto_20210406_1135.py

@ -6,12 +6,15 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0010_auto_20210406_1101'), ("casas", "0010_auto_20210406_1101"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='tipoorgao', name="tipoorgao",
options={'verbose_name': 'Tipo de \xf3rg\xe3o', 'verbose_name_plural': 'Tipos de \xf3rg\xe3o'}, options={
"verbose_name": "Tipo de \xf3rg\xe3o",
"verbose_name_plural": "Tipos de \xf3rg\xe3o",
},
), ),
] ]

4
sigi/apps/casas/migrations/0012_auto_20210406_1420.py

@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0011_auto_20210406_1135'), ("casas", "0011_auto_20210406_1135"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='tipoorgao', name="tipoorgao",
options={}, options={},
), ),
] ]

9
sigi/apps/casas/migrations/0013_auto_20210406_1428.py

@ -6,12 +6,15 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0012_auto_20210406_1420'), ("casas", "0012_auto_20210406_1420"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='tipoorgao', name="tipoorgao",
options={'verbose_name': 'Tipo de \xf3rg\xe3o', 'verbose_name_plural': 'Tipos de \xf3rg\xe3o'}, options={
"verbose_name": "Tipo de \xf3rg\xe3o",
"verbose_name_plural": "Tipos de \xf3rg\xe3o",
},
), ),
] ]

20
sigi/apps/casas/migrations/0014_auto_20210406_1945.py

@ -7,19 +7,19 @@ import sigi.apps.utils
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('contatos', '0002_auto_20151104_0810'), ("contatos", "0002_auto_20151104_0810"),
('servidores', '0001_initial'), ("servidores", "0001_initial"),
('servicos', '0004_delete_casaatendida'), ("servicos", "0004_delete_casaatendida"),
('inventario', '0001_initial'), ("inventario", "0001_initial"),
('convenios', '0002_convenio_duracao'), ("convenios", "0002_convenio_duracao"),
('ocorrencias', '0002_auto_20160308_0828'), ("ocorrencias", "0002_auto_20160308_0828"),
('eventos', '0004_remove_evento_curso_moodle_id'), ("eventos", "0004_remove_evento_curso_moodle_id"),
('casas', '0013_auto_20210406_1428'), ("casas", "0013_auto_20210406_1428"),
] ]
operations = [ operations = [
migrations.RenameModel( migrations.RenameModel(
old_name='CasaLegislativa', old_name="CasaLegislativa",
new_name='Orgao', new_name="Orgao",
), ),
] ]

20
sigi/apps/casas/migrations/0015_auto_20210407_0801.py

@ -6,22 +6,28 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0014_auto_20210406_1945'), ("casas", "0014_auto_20210406_1945"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='orgao', name="orgao",
options={'ordering': ('nome',), 'verbose_name': '\xd3rg\xe3o', 'verbose_name_plural': '\xd3rg\xe3os'}, options={
"ordering": ("nome",),
"verbose_name": "\xd3rg\xe3o",
"verbose_name_plural": "\xd3rg\xe3os",
},
), ),
migrations.AddField( migrations.AddField(
model_name='tipoorgao', model_name="tipoorgao",
name='legislativo', name="legislativo",
field=models.BooleanField(default=False, verbose_name='Poder legislativo'), field=models.BooleanField(
default=False, verbose_name="Poder legislativo"
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterUniqueTogether( migrations.AlterUniqueTogether(
name='orgao', name="orgao",
unique_together=set([]), unique_together=set([]),
), ),
] ]

13
sigi/apps/casas/migrations/0016_auto_20210407_1559.py

@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0015_auto_20210407_0801'), ("casas", "0015_auto_20210407_0801"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='gerentes_interlegis', name="gerentes_interlegis",
field=models.ManyToManyField(related_name='casas_que_gerencia', verbose_name='Gerentes Interlegis', to='servidores.Servidor', blank=True), field=models.ManyToManyField(
related_name="casas_que_gerencia",
verbose_name="Gerentes Interlegis",
to="servidores.Servidor",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

56
sigi/apps/casas/migrations/0017_auto_20210416_0841.py

@ -7,38 +7,62 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0016_auto_20210407_1559'), ("casas", "0016_auto_20210407_1559"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='casa_legislativa', name="casa_legislativa",
field=models.ForeignKey(verbose_name='\xf3rg\xe3o', to='casas.Orgao', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="\xf3rg\xe3o",
to="casas.Orgao",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='municipio', name="municipio",
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Municipio', blank=True, to='contatos.Municipio', null=True), field=models.ForeignKey(
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="Municipio",
blank=True,
to="contatos.Municipio",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='municipio', name="municipio",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Munic\xedpio', to='contatos.Municipio'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Munic\xedpio",
to="contatos.Municipio",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='pesquisador', name="pesquisador",
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Pesquisador', blank=True, to='servidores.Servidor', null=True), field=models.ForeignKey(
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="Pesquisador",
blank=True,
to="servidores.Servidor",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='tipo', name="tipo",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Tipo', to='casas.TipoOrgao'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Tipo",
to="casas.TipoOrgao",
),
preserve_default=True, preserve_default=True,
), ),
] ]

10
sigi/apps/casas/migrations/0018_orgao_sigla.py

@ -6,14 +6,16 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0017_auto_20210416_0841'), ("casas", "0017_auto_20210416_0841"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='orgao', model_name="orgao",
name='sigla', name="sigla",
field=models.CharField(max_length=30, verbose_name='sigla do \xf3rg\xe3o', blank=True), field=models.CharField(
max_length=30, verbose_name="sigla do \xf3rg\xe3o", blank=True
),
preserve_default=True, preserve_default=True,
), ),
] ]

18
sigi/apps/casas/migrations/0019_auto_20210501_1058.py

@ -6,20 +6,24 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0018_orgao_sigla'), ("casas", "0018_orgao_sigla"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='email', name="email",
field=models.CharField(max_length=250, verbose_name='e-mail', blank=True), field=models.CharField(
max_length=250, verbose_name="e-mail", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='nota', name="nota",
field=models.CharField(max_length=250, null=True, verbose_name='Telefones', blank=True), field=models.CharField(
max_length=250, null=True, verbose_name="Telefones", blank=True
),
preserve_default=True, preserve_default=True,
), ),
] ]

10
sigi/apps/casas/migrations/0020_auto_20210611_0946.py

@ -6,12 +6,16 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('casas', '0019_auto_20210501_1058'), ("casas", "0019_auto_20210501_1058"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='tipoorgao', name="tipoorgao",
options={'ordering': ('nome',), 'verbose_name': 'Tipo de \xf3rg\xe3o', 'verbose_name_plural': 'Tipos de \xf3rg\xe3o'}, options={
"ordering": ("nome",),
"verbose_name": "Tipo de \xf3rg\xe3o",
"verbose_name_plural": "Tipos de \xf3rg\xe3o",
},
), ),
] ]

371
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): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0008_alter_servico_id_alter_servidor_foto_and_more'), ("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'), "contatos",
"0005_alter_mesorregiao_options_alter_microrregiao_options_and_more",
),
("casas", "0020_auto_20210611_0946"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='orgao', name="orgao",
options={'ordering': ('nome',), 'verbose_name': 'órgão', 'verbose_name_plural': 'órgãos'}, options={
"ordering": ("nome",),
"verbose_name": "órgão",
"verbose_name_plural": "órgãos",
},
), ),
migrations.RemoveField( migrations.RemoveField(
model_name='orgao', model_name="orgao",
name='recorte', name="recorte",
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='bairro', name="bairro",
field=models.CharField(blank=True, max_length=100, verbose_name='bairro'), field=models.CharField(
blank=True, max_length=100, verbose_name="bairro"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='cargo', name="cargo",
field=models.CharField(blank=True, max_length=100, null=True, verbose_name='cargo'), field=models.CharField(
blank=True, max_length=100, null=True, verbose_name="cargo"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='data_nascimento', name="data_nascimento",
field=models.DateField(blank=True, null=True, verbose_name='data de nascimento'), field=models.DateField(
blank=True, null=True, verbose_name="data de nascimento"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='desativado', name="desativado",
field=models.BooleanField(default=False, verbose_name='desativado'), field=models.BooleanField(default=False, verbose_name="desativado"),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='endereco', name="endereco",
field=models.CharField(blank=True, max_length=100, verbose_name='endereço'), field=models.CharField(
blank=True, max_length=100, verbose_name="endereço"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='municipio', name="municipio",
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='contatos.municipio', verbose_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( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='nome', name="nome",
field=models.CharField(max_length=60, verbose_name='nome completo'), field=models.CharField(max_length=60, verbose_name="nome completo"),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='nota', name="nota",
field=models.CharField(blank=True, max_length=250, null=True, verbose_name='telefones'), field=models.CharField(
blank=True, max_length=250, null=True, verbose_name="telefones"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='observacoes', name="observacoes",
field=models.TextField(blank=True, verbose_name='observações'), field=models.TextField(blank=True, verbose_name="observações"),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='redes_sociais', name="redes_sociais",
field=models.TextField(blank=True, help_text='Colocar um por linha', verbose_name='redes sociais'), field=models.TextField(
blank=True,
help_text="Colocar um por linha",
verbose_name="redes sociais",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='setor', 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'), 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( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='sexo', name="sexo",
field=models.CharField(choices=[('M', 'Masculino'), ('F', 'Feminino')], default='M', max_length=1, verbose_name='sexo'), field=models.CharField(
choices=[("M", "Masculino"), ("F", "Feminino")],
default="M",
max_length=1,
verbose_name="sexo",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='tempo_de_servico', name="tempo_de_servico",
field=models.CharField(blank=True, max_length=50, null=True, verbose_name='tempo de serviço'), field=models.CharField(
blank=True,
max_length=50,
null=True,
verbose_name="tempo de serviço",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='funcionario', model_name="funcionario",
name='ult_alteracao', name="ult_alteracao",
field=models.DateTimeField(auto_now=True, null=True, verbose_name='última alteração'), field=models.DateTimeField(
auto_now=True, null=True, verbose_name="última alteração"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='bairro', name="bairro",
field=models.CharField(blank=True, max_length=100, verbose_name='bairro'), field=models.CharField(
blank=True, max_length=100, verbose_name="bairro"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='cnpj', name="cnpj",
field=models.CharField(blank=True, max_length=32, verbose_name='CNPJ'), field=models.CharField(
blank=True, max_length=32, verbose_name="CNPJ"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='codigo_interlegis', name="codigo_interlegis",
field=models.CharField(blank=True, max_length=3, verbose_name='código Interlegis'), field=models.CharField(
blank=True, max_length=3, verbose_name="código Interlegis"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='data_instalacao', name="data_instalacao",
field=models.DateField(blank=True, null=True, verbose_name='data de instalação da Casa Legislativa'), field=models.DateField(
blank=True,
null=True,
verbose_name="data de instalação da Casa Legislativa",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='data_levantamento', name="data_levantamento",
field=models.DateTimeField(blank=True, null=True, verbose_name='data/hora da pesquisa'), field=models.DateTimeField(
blank=True, null=True, verbose_name="data/hora da pesquisa"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='email', name="email",
field=models.EmailField(blank=True, max_length=128, verbose_name='e-mail'), field=models.EmailField(
blank=True, max_length=128, verbose_name="e-mail"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='foto', name="foto",
field=models.ImageField(blank=True, height_field='foto_altura', upload_to='imagens/casas', verbose_name='foto', width_field='foto_largura'), field=models.ImageField(
blank=True,
height_field="foto_altura",
upload_to="imagens/casas",
verbose_name="foto",
width_field="foto_largura",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='horario_funcionamento', name="horario_funcionamento",
field=models.CharField(blank=True, max_length=100, verbose_name='horário de funcionamento da Casa Legislativa'), field=models.CharField(
blank=True,
max_length=100,
verbose_name="horário de funcionamento da Casa Legislativa",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='inclusao_digital', 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'), 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( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='logradouro', name="logradouro",
field=models.CharField(help_text='Avenida, rua, praça, jardim, parque...', max_length=100, verbose_name='logradouro'), field=models.CharField(
help_text="Avenida, rua, praça, jardim, parque...",
max_length=100,
verbose_name="logradouro",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='municipio', name="municipio",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contatos.municipio', verbose_name='município'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
to="contatos.municipio",
verbose_name="município",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='nome', name="nome",
field=models.CharField(help_text='Exemplo: <em>Câmara Municipal de Pains</em>.', max_length=60, verbose_name='nome'), field=models.CharField(
help_text="Exemplo: <em>Câmara Municipal de Pains</em>.",
max_length=60,
verbose_name="nome",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='obs_pesquisa', name="obs_pesquisa",
field=models.TextField(blank=True, verbose_name='observações do pesquisador'), field=models.TextField(
blank=True, verbose_name="observações do pesquisador"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='pagina_web', name="pagina_web",
field=models.URLField(blank=True, help_text='Exemplo: <em>http://www.camarapains.mg.gov.br</em>.', verbose_name='página web'), field=models.URLField(
blank=True,
help_text="Exemplo: <em>http://www.camarapains.mg.gov.br</em>.",
verbose_name="página web",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='pesquisador', name="pesquisador",
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='servidores.servidor', verbose_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( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='search_text', name="search_text",
field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']), field=sigi.apps.utils.SearchField(
editable=False, field_names=["nome"]
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='tipo', name="tipo",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='casas.tipoorgao', verbose_name='tipo'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
to="casas.tipoorgao",
verbose_name="tipo",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='orgao', model_name="orgao",
name='ult_alt_endereco', name="ult_alt_endereco",
field=models.DateTimeField(blank=True, null=True, verbose_name='última alteração do endereço'), field=models.DateTimeField(
blank=True,
null=True,
verbose_name="última alteração do endereço",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='tipoorgao', model_name="tipoorgao",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
] ]

301
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.servidores.models import Servidor
from sigi.apps.utils import SearchField from sigi.apps.utils import SearchField
class TipoOrgao(models.Model): class TipoOrgao(models.Model):
sigla = models.CharField(_("Sigla"), max_length=5) sigla = models.CharField(_("Sigla"), max_length=5)
nome = models.CharField(_("Nome"), max_length=100) nome = models.CharField(_("Nome"), max_length=100)
legislativo = models.BooleanField(_("Poder legislativo"), default=False) legislativo = models.BooleanField(_("Poder legislativo"), default=False)
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _("Tipo de órgão") verbose_name = _("Tipo de órgão")
verbose_name_plural = _("Tipos de órgão") verbose_name_plural = _("Tipos de órgão")
def __str__(self): def __str__(self):
return self.nome return self.nome
class Orgao(models.Model): class Orgao(models.Model):
INCLUSAO_DIGITAL_CHOICES = ( INCLUSAO_DIGITAL_CHOICES = (
('NAO PESQUISADO', _('Não pesquisado')), ("NAO PESQUISADO", _("Não pesquisado")),
('NAO POSSUI PORTAL', _('Não possui portal')), ("NAO POSSUI PORTAL", _("Não possui portal")),
('PORTAL MODELO', _('Possui Portal Modelo')), ("PORTAL MODELO", _("Possui Portal Modelo")),
('OUTRO PORTAL', _('Possui outro portal')), ("OUTRO PORTAL", _("Possui outro portal")),
) )
nome = models.CharField( nome = models.CharField(
_("nome"), _("nome"),
max_length=60, max_length=60,
help_text=_('Exemplo: <em>Câmara Municipal de Pains</em>.') help_text=_("Exemplo: <em>Câmara Municipal de Pains</em>."),
)
sigla = models.CharField(
_("sigla do órgão"),
max_length=30,
blank=True
) )
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 # 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( tipo = models.ForeignKey(
TipoOrgao, TipoOrgao, on_delete=models.PROTECT, verbose_name=_("tipo")
on_delete=models.PROTECT,
verbose_name=_("tipo")
) )
cnpj = models.CharField(_("CNPJ"), max_length=32, blank=True) 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( horario_funcionamento = models.CharField(
_("horário de funcionamento da Casa Legislativa"), _("horário de funcionamento da Casa Legislativa"),
max_length=100, max_length=100,
blank=True, blank=True,
) )
codigo_interlegis = models.CharField( codigo_interlegis = models.CharField(
_('código Interlegis'), _("código Interlegis"), max_length=3, blank=True
max_length=3,
blank=True
) )
gerentes_interlegis = models.ManyToManyField( gerentes_interlegis = models.ManyToManyField(
Servidor, Servidor,
verbose_name=_("Gerentes Interlegis"), verbose_name=_("Gerentes Interlegis"),
related_name='casas_que_gerencia', related_name="casas_que_gerencia",
blank=True, blank=True,
) )
# Informações de contato # Informações de contato
logradouro = models.CharField( logradouro = models.CharField(
_("logradouro"), _("logradouro"),
max_length=100, 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) bairro = models.CharField(_("bairro"), max_length=100, blank=True)
municipio = models.ForeignKey( municipio = models.ForeignKey(
'contatos.Municipio', "contatos.Municipio",
on_delete=models.PROTECT, on_delete=models.PROTECT,
verbose_name=_('município') verbose_name=_("município"),
) )
cep = models.CharField(_("CEP"), max_length=32) 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( pagina_web = models.URLField(
_('página web'), _("página web"),
help_text=_('Exemplo: <em>http://www.camarapains.mg.gov.br</em>.'), help_text=_("Exemplo: <em>http://www.camarapains.mg.gov.br</em>."),
blank=True, blank=True,
) )
inclusao_digital = models.CharField( inclusao_digital = models.CharField(
_("inclusão digital"), _("inclusão digital"),
max_length=30, max_length=30,
choices=INCLUSAO_DIGITAL_CHOICES, choices=INCLUSAO_DIGITAL_CHOICES,
default=INCLUSAO_DIGITAL_CHOICES[0][0] default=INCLUSAO_DIGITAL_CHOICES[0][0],
) )
data_levantamento = models.DateTimeField( data_levantamento = models.DateTimeField(
_("data/hora da pesquisa"), _("data/hora da pesquisa"), null=True, blank=True
null=True,
blank=True
) )
pesquisador = models.ForeignKey( pesquisador = models.ForeignKey(
Servidor, Servidor,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
verbose_name=_("pesquisador"), verbose_name=_("pesquisador"),
null=True, null=True,
blank=True blank=True,
)
obs_pesquisa = models.TextField(
_("observações do pesquisador"),
blank=True
) )
obs_pesquisa = models.TextField(_("observações do pesquisador"), blank=True)
ult_alt_endereco = models.DateTimeField( ult_alt_endereco = models.DateTimeField(
_('última alteração do endereço'), _("última alteração do endereço"), null=True, blank=True, editable=True
null=True,
blank=True,
editable=True
) )
telefones = GenericRelation('contatos.Telefone') telefones = GenericRelation("contatos.Telefone")
foto = models.ImageField( foto = models.ImageField(
_("foto"), _("foto"),
upload_to='imagens/casas', upload_to="imagens/casas",
width_field='foto_largura', width_field="foto_largura",
height_field='foto_altura', height_field="foto_altura",
blank=True blank=True,
) )
foto_largura = models.SmallIntegerField(editable=False, null=True) foto_largura = models.SmallIntegerField(editable=False, null=True)
foto_altura = models.SmallIntegerField(editable=False, null=True) foto_altura = models.SmallIntegerField(editable=False, null=True)
data_instalacao = models.DateField( data_instalacao = models.DateField(
_('data de instalação da Casa Legislativa'), _("data de instalação da Casa Legislativa"), null=True, blank=True
null=True,
blank=True
) )
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _('órgão') verbose_name = _("órgão")
verbose_name_plural = _('órgãos') verbose_name_plural = _("órgãos")
def lista_gerentes(self, fmt='html'): def lista_gerentes(self, fmt="html"):
if not self.gerentes_interlegis.exists(): if not self.gerentes_interlegis.exists():
return "" return ""
if fmt == 'html': if fmt == "html":
return "<ul><li>"+"</li><li>".join( return (
[g.nome_completo for g in self.gerentes_interlegis.all()])+\ "<ul><li>"
"</li></ul>" + "</li><li>".join(
[g.nome_completo for g in self.gerentes_interlegis.all()]
)
+ "</li></ul>"
)
else: else:
return ", ".join([g.nome_completo for g in return ", ".join(
self.gerentes_interlegis.all()]) [g.nome_completo for g in self.gerentes_interlegis.all()]
)
@property @property
def num_parlamentares(self): def num_parlamentares(self):
@ -160,29 +149,34 @@ class Orgao(models.Model):
@property @property
def presidente(self): def presidente(self):
try: try:
if self.funcionario_set.filter(setor='presidente').count() > 1: if self.funcionario_set.filter(setor="presidente").count() > 1:
return self.funcionario_set.filter(setor='presidente')[0] return self.funcionario_set.filter(setor="presidente")[0]
else: else:
return self.funcionario_set.get(setor='presidente') return self.funcionario_set.get(setor="presidente")
except Funcionario.DoesNotExist: except Funcionario.DoesNotExist:
return None return None
@property @property
def contato_interlegis(self): def contato_interlegis(self):
try: try:
if self.funcionario_set.filter(setor='contato_interlegis').count() > 1: if (
return self.funcionario_set.filter(setor='contato_interlegis')[0] self.funcionario_set.filter(setor="contato_interlegis").count()
> 1
):
return self.funcionario_set.filter(setor="contato_interlegis")[
0
]
else: else:
return self.funcionario_set.get(setor='contato_interlegis') return self.funcionario_set.get(setor="contato_interlegis")
except Funcionario.DoesNotExist: except Funcionario.DoesNotExist:
return None return None
def gerarCodigoInterlegis(self): def gerarCodigoInterlegis(self):
codigo = self.codigo_interlegis codigo = self.codigo_interlegis
if codigo == '': if codigo == "":
if self.tipo.sigla == 'AL': # Assembléias são tratadas a parte if self.tipo.sigla == "AL": # Assembléias são tratadas a parte
codigo = 'A' + self.municipio.uf.sigla codigo = "A" + self.municipio.uf.sigla
if Orgao.objects.filter(codigo_interlegis=codigo).count() <= 0: if Orgao.objects.filter(codigo_interlegis=codigo).count() <= 0:
# Só grava o código se ele for inédito # Só grava o código se ele for inédito
self.codigo_interlegis = codigo self.codigo_interlegis = codigo
@ -190,20 +184,21 @@ class Orgao(models.Model):
return codigo return codigo
# Se já existe, então trata a Assembleia como uma Casa qualquer. # Se já existe, então trata a Assembleia como uma Casa qualquer.
cityName = normalize('NFKD', self.municipio.nome).encode( cityName = normalize("NFKD", self.municipio.nome).encode(
'ascii', 'ignore') "ascii", "ignore"
)
cityName = cityName.upper().strip() cityName = cityName.upper().strip()
cityName = cityName.replace(' DA ', ' ') cityName = cityName.replace(" DA ", " ")
cityName = cityName.replace(' DE ', ' ') cityName = cityName.replace(" DE ", " ")
cityName = cityName.replace(' DO ', ' ') cityName = cityName.replace(" DO ", " ")
cityName = filter(lambda x: x in ascii_uppercase + ' ', cityName) cityName = filter(lambda x: x in ascii_uppercase + " ", cityName)
# estratégia 1 - Pegar as 1ª letra de cada nome da cidade # 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 # Se o código ficou com menos que três letras, pegar as 2 primeiras
if len(codigo) < 3: 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ó # 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 # tem uma palavra. Pegue as três primeiras letras da palavra
@ -214,11 +209,13 @@ class Orgao(models.Model):
# última letra do nome da cidade, e ir recuando, letra a letra, # última letra do nome da cidade, e ir recuando, letra a letra,
# até achar um novo código. # até achar um novo código.
cityName = cityName.replace(' ', '') cityName = cityName.replace(" ", "")
ultima = len(cityName) ultima = len(cityName)
while Orgao.objects.filter(codigo_interlegis=codigo). \ while (
count() > 0 and ultima > 0: Orgao.objects.filter(codigo_interlegis=codigo).count() > 0
and ultima > 0
):
codigo = codigo[:2] + cityName[ultima - 1 : ultima] codigo = codigo[:2] + cityName[ultima - 1 : ultima]
ultima -= 1 ultima -= 1
@ -227,19 +224,29 @@ class Orgao(models.Model):
# três primeiras consoantes. # três primeiras consoantes.
if Orgao.objects.filter(codigo_interlegis=codigo).count() > 0: if Orgao.objects.filter(codigo_interlegis=codigo).count() > 0:
codigo_cons = cityName.replace('A', '').replace('E', '').\ codigo_cons = (
replace('I', '').replace('O', '').replace('', '')[:3] cityName.replace("A", "")
if len(codigo_cons) == 3 and \ .replace("E", "")
Orgao.objects.filter(codigo_interlegis=codigo).count() > 0: .replace("I", "")
.replace("O", "")
.replace("", "")[:3]
)
if (
len(codigo_cons) == 3
and Orgao.objects.filter(codigo_interlegis=codigo).count()
> 0
):
codigo = codigo_cons codigo = codigo_cons
# Se ainda não gerou um nome único, vamos colocar dígitos no # Se ainda não gerou um nome único, vamos colocar dígitos no
# último caractere, de A a Z # último caractere, de A a Z
i = 'A' i = "A"
while Orgao.objects.filter(codigo_interlegis=codigo). \ while (
count() > 0 and i <= 'Z': Orgao.objects.filter(codigo_interlegis=codigo).count() > 0
and i <= "Z"
):
codigo = codigo[:2] + str(i) codigo = codigo[:2] + str(i)
i = chr(ord(i) + 1) i = chr(ord(i) + 1)
@ -249,16 +256,21 @@ class Orgao(models.Model):
i = 0 i = 0
while Orgao.objects.filter(codigo_interlegis=codigo). \ while (
count() > 0 and i < 100: Orgao.objects.filter(codigo_interlegis=codigo).count() > 0
codigo = random.choice(cityName) + random.choice(cityName) + \ and i < 100
):
codigo = (
random.choice(cityName) random.choice(cityName)
+ random.choice(cityName)
+ random.choice(cityName)
)
i += 1 i += 1
# Caramba! Só resta então gerar o código com 3 letras aleatórias # Caramba! Só resta então gerar o código com 3 letras aleatórias
# quaisquer do alfabeto! # quaisquer do alfabeto!
i = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' i = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while Orgao.objects.filter(codigo_interlegis=codigo).count() > 0: while Orgao.objects.filter(codigo_interlegis=codigo).count() > 0:
codigo = random.choice(i) + random.choice(i) + random.choice(i) codigo = random.choice(i) + random.choice(i) + random.choice(i)
@ -272,25 +284,33 @@ class Orgao(models.Model):
return self.nome return self.nome
def clean(self): def clean(self):
if (hasattr(self, 'tipo') and hasattr(self, 'municipio') if (
and self.tipo.legislativo): hasattr(self, "tipo")
if Orgao.objects.filter( and hasattr(self, "municipio")
tipo=self.tipo, and self.tipo.legislativo
municipio=self.municipio).exclude(pk=self.pk).exists(): ):
if (
Orgao.objects.filter(tipo=self.tipo, municipio=self.municipio)
.exclude(pk=self.pk)
.exists()
):
raise ValidationError( raise ValidationError(
_("Já existe um(a) %(tipo)s em %(municipio)s"), _("Já existe um(a) %(tipo)s em %(municipio)s"),
code='integrity', code="integrity",
params={'tipo': self.tipo, 'municipio': self.municipio}) params={"tipo": self.tipo, "municipio": self.municipio},
)
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
address_changed = False address_changed = False
if self.pk is not None: if self.pk is not None:
original = Orgao.objects.get(pk=self.pk) original = Orgao.objects.get(pk=self.pk)
if (self.logradouro != original.logradouro or if (
self.bairro != original.bairro or self.logradouro != original.logradouro
self.municipio != original.municipio or or self.bairro != original.bairro
self.cep != original.cep): or self.municipio != original.municipio
or self.cep != original.cep
):
address_changed = True address_changed = True
else: else:
address_changed = True address_changed = True
@ -300,108 +320,93 @@ class Orgao(models.Model):
return super(Orgao, self).save(*args, **kwargs) return super(Orgao, self).save(*args, **kwargs)
class Funcionario(models.Model): class Funcionario(models.Model):
SETOR_CHOICES = [ SETOR_CHOICES = [
("presidente", _("Presidente")), ("presidente", _("Presidente")),
("contato_interlegis", _("Contato Interlegis")), ("contato_interlegis", _("Contato Interlegis")),
("infraestrutura_fisica", _("Infraestrutura Física")), ("infraestrutura_fisica", _("Infraestrutura Física")),
("estrutura_de_ti", _("Estrutura de TI")), ("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")), ("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")), ("estrutura_de_recursos_humanos", _("Estrutura de Recursos Humanos")),
("gestao", _("Gestão")), ("gestao", _("Gestão")),
("outros", _("Outros")), ("outros", _("Outros")),
] ]
SEXO_CHOICES = [ SEXO_CHOICES = [("M", _("Masculino")), ("F", _("Feminino"))]
("M", _("Masculino")),
("F", _("Feminino"))
]
casa_legislativa = models.ForeignKey( casa_legislativa = models.ForeignKey(
Orgao, Orgao,
on_delete=models.CASCADE, on_delete=models.CASCADE,
verbose_name=_("órgão"), 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 = models.CharField(
_("sexo"), _("sexo"), max_length=1, choices=SEXO_CHOICES, default="M"
max_length=1,
choices=SEXO_CHOICES,
default="M"
) )
data_nascimento = models.DateField( data_nascimento = models.DateField(
_("data de nascimento"), _("data de nascimento"), blank=True, null=True
blank=True,
null=True
) )
nota = models.CharField( nota = models.CharField(
_("telefones"), _("telefones"), max_length=250, null=True, blank=True
max_length=250,
null=True,
blank=True
) )
email = models.CharField(_('e-mail'), max_length=250, blank=True) email = models.CharField(_("e-mail"), max_length=250, blank=True)
endereco = models.CharField(_('endereço'), max_length=100, blank=True) endereco = models.CharField(_("endereço"), max_length=100, blank=True)
municipio = models.ForeignKey( municipio = models.ForeignKey(
Municipio, Municipio,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
verbose_name=_('municipio'), verbose_name=_("municipio"),
null=True, null=True,
blank=True, blank=True,
) )
bairro = models.CharField(_('bairro'), max_length=100, blank=True) bairro = models.CharField(_("bairro"), max_length=100, blank=True)
cep = models.CharField(_('CEP'), max_length=10, blank=True) cep = models.CharField(_("CEP"), max_length=10, blank=True)
redes_sociais = models.TextField( redes_sociais = models.TextField(
_('redes sociais'), _("redes sociais"), help_text=_("Colocar um por linha"), blank=True
help_text=_('Colocar um por linha'),
blank=True
) )
cargo = models.CharField(_("cargo"), max_length=100, null=True, blank=True) cargo = models.CharField(_("cargo"), max_length=100, null=True, blank=True)
funcao = models.CharField( funcao = models.CharField(
_('função'), _("função"), max_length=100, null=True, blank=True
max_length=100,
null=True,
blank=True
) )
setor = models.CharField( setor = models.CharField(
_("setor"), _("setor"), max_length=100, choices=SETOR_CHOICES, default="outros"
max_length=100,
choices=SETOR_CHOICES,
default="outros"
) )
tempo_de_servico = models.CharField( tempo_de_servico = models.CharField(
_('tempo de serviço'), _("tempo de serviço"), max_length=50, null=True, blank=True
max_length=50,
null=True,
blank=True
) )
ult_alteracao = models.DateTimeField( ult_alteracao = models.DateTimeField(
_('última alteração'), _("última alteração"),
null=True, null=True,
blank=True, blank=True,
editable=True, editable=True,
auto_now=True auto_now=True,
) )
desativado = models.BooleanField(_("desativado"), default=False) desativado = models.BooleanField(_("desativado"), default=False)
observacoes = models.TextField(_("observações"), blank=True) observacoes = models.TextField(_("observações"), blank=True)
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _('contato da Casa Legislativa') verbose_name = _("contato da Casa Legislativa")
verbose_name_plural = _('contatos da Casa Legislativa') verbose_name_plural = _("contatos da Casa Legislativa")
def __str__(self): def __str__(self):
return self.nome return self.nome
class PresidenteManager(models.Manager): class PresidenteManager(models.Manager):
def get_queryset(self): def get_queryset(self):
qs = super(PresidenteManager, self).get_queryset() qs = super(PresidenteManager, self).get_queryset()
qs = qs.filter(setor='presidente') qs = qs.filter(setor="presidente")
return qs return qs
class Presidente(Funcionario): class Presidente(Funcionario):
class Meta: class Meta:
proxy = True proxy = True
@ -409,7 +414,7 @@ class Presidente(Funcionario):
objects = PresidenteManager() objects = PresidenteManager()
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
self.setor = 'presidente' self.setor = "presidente"
self.cargo = 'Presidente' self.cargo = "Presidente"
self.funcao = 'Presidente' self.funcao = "Presidente"
return super(Presidente, self).save(*args, **kwargs) return super(Presidente, self).save(*args, **kwargs)

15
sigi/apps/casas/test_casas.py

@ -6,12 +6,21 @@ from sigi.apps.casas.models import Orgao
@pytest.fixture @pytest.fixture
def some_parliaments(): def some_parliaments():
return parliaments_from_names([ return parliaments_from_names(
[
"Assembleia Legislativa do Amapa", "Assembleia Legislativa do Amapa",
"Camara Municipal de Fortaleza", "Camara Municipal de Fortaleza",
"Camara Legislativa do Distrito Federal", "Camara Legislativa do Distrito Federal",
]) ]
)
def parliaments_from_names(names): 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
]

9
sigi/apps/casas/urls.py

@ -2,9 +2,12 @@ from django.urls import path, include
from sigi.apps.casas import views from sigi.apps.casas import views
urlpatterns = [ urlpatterns = [
path('orgao/casas_sem_convenio_report/', views.CasasSemConvenioReport.as_view(), path(
name='casas-sem-convenio-report'), "orgao/casas_sem_convenio_report/",
path('carteira/', views.painel_relacionamento, name='casas-carteira'), views.CasasSemConvenioReport.as_view(),
name="casas-sem-convenio-report",
),
path("carteira/", views.painel_relacionamento, name="casas-carteira"),
] ]

355
sigi/apps/casas/views.py

@ -9,8 +9,11 @@ from django.conf import settings
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Count, Q from django.db.models import Count, Q
from django.http import (HttpResponse, HttpResponseRedirect, from django.http import (
HttpResponseForbidden) HttpResponse,
HttpResponseRedirect,
HttpResponseForbidden,
)
from django.shortcuts import render, get_object_or_404 from django.shortcuts import render, get_object_or_404
from django.utils.translation import gettext as _, ngettext from django.utils.translation import gettext as _, ngettext
from django.views.generic import View 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.forms import PortfolioForm, AtualizaCasaForm
from sigi.apps.casas.models import Orgao, TipoOrgao, Funcionario from sigi.apps.casas.models import Orgao, TipoOrgao, Funcionario
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
# from sigi.shortcuts import render_to_pdf # from sigi.shortcuts import render_to_pdf
# from sigi.apps.casas.reports import (CasasLegislativasLabels, # from sigi.apps.casas.reports import (CasasLegislativasLabels,
# CasasLegislativasLabelsSemPresidente) # CasasLegislativasLabelsSemPresidente)
from sigi.apps.contatos.models import (UnidadeFederativa, Mesorregiao, from sigi.apps.contatos.models import (
Microrregiao) UnidadeFederativa,
Mesorregiao,
Microrregiao,
)
# , Municipio # , Municipio
from sigi.apps.ocorrencias.models import Ocorrencia from sigi.apps.ocorrencias.models import Ocorrencia
# from sigi.apps.parlamentares.reports import ParlamentaresLabels # from sigi.apps.parlamentares.reports import ParlamentaresLabels
from sigi.apps.servicos.models import TipoServico from sigi.apps.servicos.models import TipoServico
class CasasSemConvenioReport(WeasyTemplateView): class CasasSemConvenioReport(WeasyTemplateView):
template_name = "casas/casas_sem_convenio_pdf.html" 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): def get_context_data(self, **kwargs):
qs = Orgao.objects.filter(convenio=None).order_by( qs = Orgao.objects.filter(convenio=None).order_by(
'municipio__uf', "municipio__uf", "nome"
'nome'
)
qs = Orgao.objects.order_by(
'municipio__uf',
'nome'
) )
qs = Orgao.objects.order_by("municipio__uf", "nome")
if self.request.GET: if self.request.GET:
qs = get_for_qs(self.request.GET, qs) qs = get_for_qs(self.request.GET, qs)
if not 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): def get_for_qs(get, qs):
kwargs = {} kwargs = {}
for k, v in get.items(): 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 kwargs[str(k)] = v
# if 'convenio' in kwargs: # if 'convenio' in kwargs:
@ -90,32 +97,32 @@ def get_for_qs(get, qs):
# del(kwargs['servico']) # del(kwargs['servico'])
qs = qs.filter(**kwargs) qs = qs.filter(**kwargs)
if 'o' in get: if "o" in get:
qs = query_ordena(qs, get['o']) qs = query_ordena(qs, get["o"])
return qs return qs
# @param qs: queryset # @param qs: queryset
# @param o: (int) number of order field # @param o: (int) number of order field
def query_ordena(qs, o): def query_ordena(qs, o):
from sigi.apps.casas.admin import OrgaoAdmin from sigi.apps.casas.admin import OrgaoAdmin
list_display = OrgaoAdmin.list_display list_display = OrgaoAdmin.list_display
order_fields = [] order_fields = []
for order_number in o.split('.'): for order_number in o.split("."):
order_number = int(order_number) order_number = int(order_number)
order = '' order = ""
if order_number != abs(order_number): if order_number != abs(order_number):
order_number = abs(order_number) order_number = abs(order_number)
order = '-' order = "-"
order_fields.append(order + list_display[order_number - 1]) order_fields.append(order + list_display[order_number - 1])
qs = qs.order_by(*order_fields) qs = qs.order_by(*order_fields)
return qs return qs
# class importa_casas(View): # class importa_casas(View):
# errors = [] # errors = []
# total_registros = 0 # total_registros = 0
@ -405,7 +412,6 @@ def query_ordena(qs, o):
# return len(self.errors) == 0 # return len(self.errors) == 0
# def get_for_qs(get, qs): # def get_for_qs(get, qs):
# """ # """
# Verifica atributos do GET e retorna queryset correspondente # Verifica atributos do GET e retorna queryset correspondente
@ -913,109 +919,130 @@ def query_ordena(qs, o):
def resumo_carteira(casas): def resumo_carteira(casas):
regioes = {r[0]: 0 for r in UnidadeFederativa.REGIAO_CHOICES} regioes = {r[0]: 0 for r in UnidadeFederativa.REGIAO_CHOICES}
regioes['total'] = 0 regioes["total"] = 0
total = regioes.copy() total = regioes.copy()
sem_produto = regioes.copy() sem_produto = regioes.copy()
tipos_servico = TipoServico.objects.all() tipos_servico = TipoServico.objects.all()
dados = {ts.id: regioes.copy() for ts in tipos_servico} dados = {ts.id: regioes.copy() for ts in tipos_servico}
for r in casas.values('municipio__uf__regiao').annotate( for r in (
quantidade=Count('id')).order_by(): casas.values("municipio__uf__regiao")
regiao = r['municipio__uf__regiao'] .annotate(quantidade=Count("id"))
quantidade = r['quantidade'] .order_by()
):
regiao = r["municipio__uf__regiao"]
quantidade = r["quantidade"]
total[regiao] = quantidade total[regiao] = quantidade
total['total'] += quantidade total["total"] += quantidade
for r in casas.values('municipio__uf__regiao', for r in (
'servico__tipo_servico__id').annotate( casas.values("municipio__uf__regiao", "servico__tipo_servico__id")
quantidade=Count('id')).order_by(): .annotate(quantidade=Count("id"))
regiao = r['municipio__uf__regiao'] .order_by()
servico = r['servico__tipo_servico__id'] ):
quantidade = r['quantidade'] regiao = r["municipio__uf__regiao"]
servico = r["servico__tipo_servico__id"]
quantidade = r["quantidade"]
if servico is None: if servico is None:
sem_produto[regiao] = quantidade sem_produto[regiao] = quantidade
sem_produto['total'] += quantidade sem_produto["total"] += quantidade
else: else:
dados[servico][regiao] = quantidade dados[servico][regiao] = quantidade
dados[servico]['total'] += quantidade dados[servico]["total"] += quantidade
dados_ocorrencia = { dados_ocorrencia = {
'registradas': regioes.copy(), "registradas": regioes.copy(),
'pendentes': regioes.copy(), "pendentes": regioes.copy(),
'sem': regioes.copy(), "sem": regioes.copy(),
'media': regioes.copy(), "media": regioes.copy(),
} }
for r in casas.values('ocorrencia__status', for r in (
'municipio__uf__regiao').annotate( casas.values("ocorrencia__status", "municipio__uf__regiao")
quantidade=Count('id')).order_by(): .annotate(quantidade=Count("id"))
status = r['ocorrencia__status'] .order_by()
regiao = r['municipio__uf__regiao'] ):
quantidade = r['quantidade'] status = r["ocorrencia__status"]
regiao = r["municipio__uf__regiao"]
quantidade = r["quantidade"]
if status is None: if status is None:
dados_ocorrencia['sem'][regiao] += quantidade dados_ocorrencia["sem"][regiao] += quantidade
dados_ocorrencia['sem']['total'] += quantidade dados_ocorrencia["sem"]["total"] += quantidade
else: else:
dados_ocorrencia['registradas'][regiao] += quantidade dados_ocorrencia["registradas"][regiao] += quantidade
dados_ocorrencia['registradas']['total'] += quantidade dados_ocorrencia["registradas"]["total"] += quantidade
if status in [Ocorrencia.STATUS_ABERTO, Ocorrencia.STATUS_REABERTO]: if status in [Ocorrencia.STATUS_ABERTO, Ocorrencia.STATUS_REABERTO]:
dados_ocorrencia['pendentes'][regiao] += quantidade dados_ocorrencia["pendentes"][regiao] += quantidade
dados_ocorrencia['pendentes']['total'] += quantidade dados_ocorrencia["pendentes"]["total"] += quantidade
for r in regioes: for r in regioes:
if (total[r] - dados_ocorrencia['sem'][r]) == 0: if (total[r] - dados_ocorrencia["sem"][r]) == 0:
dados_ocorrencia['media'][r] = 0 dados_ocorrencia["media"][r] = 0
else: else:
dados_ocorrencia['media'][r] = ( dados_ocorrencia["media"][r] = (
1.0 * dados_ocorrencia['registradas'][r] / 1.0
(total[r] - dados_ocorrencia['sem'][r]) * dados_ocorrencia["registradas"][r]
/ (total[r] - dados_ocorrencia["sem"][r])
) )
resumo = [ resumo = [
[_("Item"), _("Total nacional")] + [_("Item"), _("Total nacional")]
[r[1] for r in UnidadeFederativa.REGIAO_CHOICES] + [r[1] for r in UnidadeFederativa.REGIAO_CHOICES]
] ]
resumo.append( resumo.append(
[_("Casas em sua carteira"), total['total']] + [_("Casas em sua carteira"), total["total"]]
[total[r[0]] for r in UnidadeFederativa.REGIAO_CHOICES] + [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( resumo.append(
[_("Casas sem nenhum produto"), sem_produto['total']] + [_("Casas sem nenhum produto"), sem_produto["total"]]
[sem_produto[r[0]] for r in UnidadeFederativa.REGIAO_CHOICES] + [sem_produto[r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
) )
resumo.extend( resumo.extend(
[[ts.nome, dados[ts.id]['total']] + [
[dados[ts.id][r[0]] for r in UnidadeFederativa.REGIAO_CHOICES] [ts.nome, dados[ts.id]["total"]]
+ [dados[ts.id][r[0]] for r in UnidadeFederativa.REGIAO_CHOICES]
for ts in tipos_servico 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( resumo.append(
[_("Casas que nunca registraram ocorrências"), [
dados_ocorrencia['sem']['total']] + _("Casas que nunca registraram ocorrências"),
[dados_ocorrencia['sem'][r[0]] dados_ocorrencia["sem"]["total"],
]
+ [
dados_ocorrencia["sem"][r[0]]
for r in UnidadeFederativa.REGIAO_CHOICES for r in UnidadeFederativa.REGIAO_CHOICES
] ]
) )
resumo.append( resumo.append(
[_("Total de ocorrências registradas"), [
dados_ocorrencia['registradas']['total']] + _("Total de ocorrências registradas"),
[dados_ocorrencia['registradas'][r[0]] dados_ocorrencia["registradas"]["total"],
]
+ [
dados_ocorrencia["registradas"][r[0]]
for r in UnidadeFederativa.REGIAO_CHOICES for r in UnidadeFederativa.REGIAO_CHOICES
] ]
) )
resumo.append( resumo.append(
[_("Total de ocorrências pendentes"), [
dados_ocorrencia['pendentes']['total']] + _("Total de ocorrências pendentes"),
[dados_ocorrencia['pendentes'][r[0]] dados_ocorrencia["pendentes"]["total"],
]
+ [
dados_ocorrencia["pendentes"][r[0]]
for r in UnidadeFederativa.REGIAO_CHOICES for r in UnidadeFederativa.REGIAO_CHOICES
] ]
) )
resumo.append( resumo.append(
[_("Média de ocorrências por casa"), [
round(dados_ocorrencia['media']['total'], 2)] + _("Média de ocorrências por casa"),
[round(dados_ocorrencia['media'][r[0]], 2) round(dados_ocorrencia["media"]["total"], 2),
]
+ [
round(dados_ocorrencia["media"][r[0]], 2)
for r in UnidadeFederativa.REGIAO_CHOICES for r in UnidadeFederativa.REGIAO_CHOICES
] ]
) )
@ -1024,84 +1051,84 @@ def resumo_carteira(casas):
def casas_carteira(request, casas, context): def casas_carteira(request, casas, context):
servicos = request.GET.getlist('servico') servicos = request.GET.getlist("servico")
sigla_regiao = request.GET.get('r', None) sigla_regiao = request.GET.get("r", None)
sigla_uf = request.GET.get('uf', None) sigla_uf = request.GET.get("uf", None)
meso_id = request.GET.get('meso', None) meso_id = request.GET.get("meso", None)
micro_id = request.GET.get('micro', None) micro_id = request.GET.get("micro", None)
servicos = request.GET.getlist('servico') servicos = request.GET.getlist("servico")
tipos_servico = context['servicos'] tipos_servico = context["servicos"]
context['qs_regiao'] = '' context["qs_regiao"] = ""
if micro_id is not None: if micro_id is not None:
context['micro'] = get_object_or_404(Microrregiao, pk=micro_id) context["micro"] = get_object_or_404(Microrregiao, pk=micro_id)
context['qs_regiao'] = 'micro=%s' % micro_id context["qs_regiao"] = "micro=%s" % micro_id
context['meso'] = context['micro'].mesorregiao context["meso"] = context["micro"].mesorregiao
context['uf'] = context['meso'].uf context["uf"] = context["meso"].uf
context['regiao'] = context['uf'].regiao context["regiao"] = context["uf"].regiao
casas = casas.filter(municipio__microrregiao=context['micro']) casas = casas.filter(municipio__microrregiao=context["micro"])
elif meso_id is not None: elif meso_id is not None:
context['meso'] = get_object_or_404(Mesorregiao, pk=meso_id) context["meso"] = get_object_or_404(Mesorregiao, pk=meso_id)
context['qs_regiao'] = 'meso=%s' % meso_id context["qs_regiao"] = "meso=%s" % meso_id
context['uf'] = context['meso'].uf context["uf"] = context["meso"].uf
context['regiao'] = context['uf'].regiao context["regiao"] = context["uf"].regiao
casas = casas.filter( casas = casas.filter(
municipio__microrregiao__mesorregiao=context['meso'] municipio__microrregiao__mesorregiao=context["meso"]
) )
elif sigla_uf is not None: elif sigla_uf is not None:
context['uf'] = get_object_or_404(UnidadeFederativa, sigla=sigla_uf) context["uf"] = get_object_or_404(UnidadeFederativa, sigla=sigla_uf)
context['qs_regiao'] = 'uf=%s' % sigla_uf context["qs_regiao"] = "uf=%s" % sigla_uf
context['regiao'] = context['uf'].regiao context["regiao"] = context["uf"].regiao
casas = casas.filter(municipio__uf=context['uf']) casas = casas.filter(municipio__uf=context["uf"])
elif sigla_regiao is not None: elif sigla_regiao is not None:
context['regiao'] = sigla_regiao context["regiao"] = sigla_regiao
context['qs_regiao'] = 'r=%s' % sigla_regiao context["qs_regiao"] = "r=%s" % sigla_regiao
casas = casas.filter(municipio__uf__regiao=sigla_regiao) casas = casas.filter(municipio__uf__regiao=sigla_regiao)
if 'regiao' in context: if "regiao" in context:
context['ufs'] = UnidadeFederativa.objects.filter( context["ufs"] = UnidadeFederativa.objects.filter(
regiao=context['regiao'] 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): if not servicos or set(servicos) == set(todos_servicos):
servicos = todos_servicos servicos = todos_servicos
context['qs_servico'] = '' context["qs_servico"] = ""
else: else:
if '_none_' in servicos: if "_none_" in servicos:
casas = casas.filter( casas = casas.filter(
Q(servico=None) | Q(servico__tipo_servico__sigla__in=servicos) Q(servico=None) | Q(servico__tipo_servico__sigla__in=servicos)
) )
else: else:
casas = casas.filter(servico__tipo_servico__sigla__in=servicos) casas = casas.filter(servico__tipo_servico__sigla__in=servicos)
casas = casas.distinct('nome', 'municipio__uf') casas = casas.distinct("nome", "municipio__uf")
context['qs_servico'] = "&".join(['servico=%s' % s for s in servicos]) context["qs_servico"] = "&".join(["servico=%s" % s for s in servicos])
context['servicos_check'] = servicos context["servicos_check"] = servicos
casas = casas.select_related( casas = casas.select_related(
'municipio', "municipio",
'municipio__uf', "municipio__uf",
'municipio__microrregiao', "municipio__microrregiao",
'municipio__microrregiao__mesorregiao' "municipio__microrregiao__mesorregiao",
).prefetch_related('servico_set') ).prefetch_related("servico_set")
return casas, context return casas, context
@login_required @login_required
def painel_relacionamento(request): def painel_relacionamento(request):
page = request.GET.get('page', 1) page = request.GET.get("page", 1)
snippet = request.GET.get('snippet', '') snippet = request.GET.get("snippet", "")
seletor = request.GET.get('s', None) seletor = request.GET.get("s", None)
servidor = request.GET.get('servidor', None) servidor = request.GET.get("servidor", None)
fmt = request.GET.get('f', 'html') fmt = request.GET.get("f", "html")
if servidor is None: if servidor is None:
gerente = request.user.servidor gerente = request.user.servidor
elif servidor == '_all': elif servidor == "_all":
gerente = None gerente = None
else: else:
gerente = get_object_or_404(Servidor, pk=servidor) gerente = get_object_or_404(Servidor, pk=servidor)
@ -1117,59 +1144,73 @@ def painel_relacionamento(request):
regioes = UnidadeFederativa.REGIAO_CHOICES regioes = UnidadeFederativa.REGIAO_CHOICES
context = { context = {
'seletor': seletor, "seletor": seletor,
'snippet': snippet, "snippet": snippet,
'regioes': regioes, "regioes": regioes,
'servicos': tipos_servico, "servicos": tipos_servico,
'gerentes': Servidor.objects.exclude(casas_que_gerencia=None), "gerentes": Servidor.objects.exclude(casas_que_gerencia=None),
'gerente': gerente, "gerente": gerente,
'qs_servidor': ('servidor=%s' % gerente.pk) if gerente else '', "qs_servidor": ("servidor=%s" % gerente.pk) if gerente else "",
} }
if snippet != 'lista': if snippet != "lista":
context['resumo'] = resumo_carteira(casas) context["resumo"] = resumo_carteira(casas)
if snippet != 'resumo': if snippet != "resumo":
casas, context = casas_carteira(request, casas, context) casas, context = casas_carteira(request, casas, context)
paginator = Paginator(casas, 30) paginator = Paginator(casas, 30)
try: try:
pagina = paginator.page(page) pagina = paginator.page(page)
except (EmptyPage, InvalidPage): except (EmptyPage, InvalidPage):
pagina = paginator.page(paginator.num_pages) pagina = paginator.page(paginator.num_pages)
context['page_obj'] = pagina context["page_obj"] = pagina
if snippet == 'lista': if snippet == "lista":
if fmt == 'csv': if fmt == "csv":
response = HttpResponse(content_type='text/csv') response = HttpResponse(content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename=casas.csv' response["Content-Disposition"] = "attachment; filename=casas.csv"
writer = csv.writer(response) writer = csv.writer(response)
writer.writerow([_("Casa legislativa"), _("Região"), _("Estado"), writer.writerow(
_("Mesorregião"), _("Microrregião"), [
_("Gerentes Interlegis"), _("Serviços"),]) _("Casa legislativa"),
_("Região"),
_("Estado"),
_("Mesorregião"),
_("Microrregião"),
_("Gerentes Interlegis"),
_("Serviços"),
]
)
for c in casas: for c in casas:
writer.writerow([ writer.writerow(
[
c.nome, c.nome,
c.municipio.uf.get_regiao_display(), c.municipio.uf.get_regiao_display(),
c.municipio.uf.sigla, c.municipio.uf.sigla,
c.municipio.microrregiao.mesorregiao.nome, c.municipio.microrregiao.mesorregiao.nome,
c.municipio.microrregiao.nome, c.municipio.microrregiao.nome,
c.lista_gerentes(fmt='lista'), c.lista_gerentes(fmt="lista"),
(", ".join( (
[s.tipo_servico.nome for s in c.servico_set.filter( ", ".join(
data_desativacao__isnull=True) [
]) s.tipo_servico.nome
for s in c.servico_set.filter(
data_desativacao__isnull=True
)
]
)
), ),
]) ]
)
return response return response
return render( return render(
request, request, "casas/lista_casas_carteira_snippet.html", context
'casas/lista_casas_carteira_snippet.html',
context
) )
if snippet == 'resumo': if snippet == "resumo":
return render(request, 'casas/resumo_carteira_snippet.html', context) 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 # @login_required
# def gerentes_interlegis(request): # def gerentes_interlegis(request):

132
sigi/apps/contatos/admin.py

@ -2,74 +2,130 @@ from django.contrib import admin
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from sigi.apps.utils.filters import RangeFilter from sigi.apps.utils.filters import RangeFilter
from sigi.apps.contatos.models import (UnidadeFederativa, Mesorregiao, from sigi.apps.contatos.models import (
Microrregiao, Municipio, Telefone, UnidadeFederativa,
Contato) Mesorregiao,
Microrregiao,
Municipio,
Telefone,
Contato,
)
from sigi.apps.utils import queryset_ascii from sigi.apps.utils import queryset_ascii
class MesorregiaoInline(admin.TabularInline): class MesorregiaoInline(admin.TabularInline):
model = Mesorregiao model = Mesorregiao
class MicrorregiaoInline(admin.TabularInline): class MicrorregiaoInline(admin.TabularInline):
model = Microrregiao model = Microrregiao
@admin.register(UnidadeFederativa) @admin.register(UnidadeFederativa)
class UnidadeFederativaAdmin(admin.ModelAdmin): class UnidadeFederativaAdmin(admin.ModelAdmin):
actions = None actions = None
list_display = ('codigo_ibge', 'nome', 'sigla', 'regiao', 'populacao') list_display = ("codigo_ibge", "nome", "sigla", "regiao", "populacao")
list_display_links = ('codigo_ibge', 'nome') list_display_links = ("codigo_ibge", "nome")
list_filter = ('regiao', ('populacao', RangeFilter),) list_filter = (
search_fields = ('search_text', 'codigo_ibge', 'sigla', 'regiao') "regiao",
("populacao", RangeFilter),
)
search_fields = ("search_text", "codigo_ibge", "sigla", "regiao")
get_queryset = queryset_ascii get_queryset = queryset_ascii
inlines = (MesorregiaoInline,) inlines = (MesorregiaoInline,)
@admin.register(Mesorregiao) @admin.register(Mesorregiao)
class MesorregiaoAdmin(admin.ModelAdmin): class MesorregiaoAdmin(admin.ModelAdmin):
actions = None actions = None
list_display = ('codigo_ibge', 'uf', 'nome') list_display = ("codigo_ibge", "uf", "nome")
list_display_links = ('codigo_ibge', 'nome') list_display_links = ("codigo_ibge", "nome")
list_filter = ('uf',) list_filter = ("uf",)
search_fields = ('uf__search_text', 'search_text', 'codigo_ibge', search_fields = (
'uf__sigla') "uf__search_text",
"search_text",
"codigo_ibge",
"uf__sigla",
)
get_queryset = queryset_ascii get_queryset = queryset_ascii
inlines = (MicrorregiaoInline,) inlines = (MicrorregiaoInline,)
@admin.register(Municipio) @admin.register(Municipio)
class MunicipioAdmin(admin.ModelAdmin): class MunicipioAdmin(admin.ModelAdmin):
actions = None actions = None
list_display = ('codigo_ibge', 'codigo_tse', 'nome', 'uf', 'is_capital', list_display = (
'populacao', 'is_polo', 'idh', 'pib_ano', 'pib_total', "codigo_ibge",
'pib_percapita') "codigo_tse",
list_display_links = ('codigo_ibge', 'codigo_tse', 'nome') "nome",
list_filter = ('is_capital', 'is_polo', ('idh', RangeFilter), "uf",
('populacao', RangeFilter), 'uf__regiao', '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 get_queryset = queryset_ascii
fieldsets = ( fieldsets = (
(None, { (
'fields': ('codigo_ibge', 'codigo_tse', 'nome', 'data_criacao', None,
'uf', 'microrregiao', 'is_capital', 'populacao', {
'is_polo', 'idh', 'pib_ano', 'pib_total', "fields": (
'pib_percapita') "codigo_ibge",
}), "codigo_tse",
(_('Posição geográfica'), { "nome",
'fields': ('latitude', 'longitude'), "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) @admin.register(Telefone)
class TelefoneAdmin(admin.ModelAdmin): class TelefoneAdmin(admin.ModelAdmin):
list_display = ('numero', 'tipo', 'nota') list_display = ("numero", "tipo", "nota")
list_display_links = ('numero',) list_display_links = ("numero",)
list_filter = ('tipo',) list_filter = ("tipo",)
radio_fields = {'tipo': admin.VERTICAL} radio_fields = {"tipo": admin.VERTICAL}
search_fields = ('numero', 'tipo', 'nota') search_fields = ("numero", "tipo", "nota")
@admin.register(Contato) @admin.register(Contato)
class ContatoAdmin(admin.ModelAdmin): class ContatoAdmin(admin.ModelAdmin):
list_display = ('nome', 'nota', 'email', 'municipio') list_display = ("nome", "nota", "email", "municipio")
list_display_links = ('nome',) list_display_links = ("nome",)
list_filter = ('nome',) list_filter = ("nome",)
search_fields = ('nome', 'nota', 'email', 'municipio__nome', search_fields = (
'municipio__uf__nome') "nome",
"nota",
"email",
"municipio__nome",
"municipio__uf__nome",
)

5
sigi/apps/contatos/apps.py

@ -1,6 +1,7 @@
from django.apps import AppConfig from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class ContatosConfig(AppConfig): class ContatosConfig(AppConfig):
name = 'sigi.apps.contatos' name = "sigi.apps.contatos"
verbose_name = _('contatos') verbose_name = _("contatos")

87
sigi/apps/contatos/management/commands/importa_mesomicro.py

@ -24,7 +24,13 @@
import csv import csv
import os import os
from django.core.management.base import BaseCommand, CommandError 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): class Command(BaseCommand):
args = "data_file.csv" args = "data_file.csv"
@ -40,8 +46,14 @@ class Command(BaseCommand):
* Os nomes dos campos devem ser grafados exatamente como descrito.""" * Os nomes dos campos devem ser grafados exatamente como descrito."""
campos = {'cod_uf', 'cod_mesorregiao', 'nome_mesorregiao', 'cod_microrregiao', campos = {
'nome_microrregiao', 'cod_municipio'} "cod_uf",
"cod_mesorregiao",
"nome_mesorregiao",
"cod_microrregiao",
"nome_microrregiao",
"cod_municipio",
}
def handle(self, *args, **options): def handle(self, *args, **options):
if len(args) != 1: if len(args) != 1:
@ -50,51 +62,86 @@ class Command(BaseCommand):
file_name = args[0] file_name = args[0]
if not os.path.isfile(file_name): if not os.path.isfile(file_name):
raise CommandError("Arquivo %s não encontrado" % [file_name,]) raise CommandError(
"Arquivo %s não encontrado"
with open(file_name, 'rb') as csvfile: % [
file_name,
]
)
with open(file_name, "rb") as csvfile:
reader = csv.DictReader(csvfile) reader = csv.DictReader(csvfile)
if not self.campos.issubset(reader.fieldnames): 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 erros = 0
for reg in reader: for reg in reader:
try: try:
uf = UnidadeFederativa.objects.get(codigo_ibge=reg['cod_uf']) uf = UnidadeFederativa.objects.get(
codigo_ibge=reg["cod_uf"]
)
except UnidadeFederativa.DoesNotExist: except UnidadeFederativa.DoesNotExist:
self.stdout.write("(Linha %s): não existe UF com código IBGE '%s'" % self.stdout.write(
(reader.line_num, reg['cod_uf'],)) "(Linha %s): não existe UF com código IBGE '%s'"
% (
reader.line_num,
reg["cod_uf"],
)
)
erros = erros + 1 erros = erros + 1
continue continue
try: try:
municipio = Municipio.objects.get(codigo_ibge=reg['cod_municipio']) municipio = Municipio.objects.get(
codigo_ibge=reg["cod_municipio"]
)
except Municipio.DoesNotExist: except Municipio.DoesNotExist:
self.stdout.write("(Linha %s): não existe Município com código IBGE '%s'" % self.stdout.write(
(reader.line_num, reg['cod_municipio'],)) "(Linha %s): não existe Município com código IBGE '%s'"
% (
reader.line_num,
reg["cod_municipio"],
)
)
erros = erros + 1 erros = erros + 1
continue continue
cod_meso = reg['cod_uf'] + reg['cod_mesorregiao'] cod_meso = reg["cod_uf"] + reg["cod_mesorregiao"]
cod_micro = cod_meso + reg['cod_microrregiao'] cod_micro = cod_meso + reg["cod_microrregiao"]
if Mesorregiao.objects.filter(codigo_ibge=cod_meso).exists(): if Mesorregiao.objects.filter(codigo_ibge=cod_meso).exists():
meso = Mesorregiao.objects.get(codigo_ibge=cod_meso) meso = Mesorregiao.objects.get(codigo_ibge=cod_meso)
else: else:
meso = Mesorregiao(codigo_ibge=cod_meso, uf=uf, nome=reg['nome_mesorregiao']) meso = Mesorregiao(
meso.nome = reg['nome_mesorregiao'] codigo_ibge=cod_meso,
uf=uf,
nome=reg["nome_mesorregiao"],
)
meso.nome = reg["nome_mesorregiao"]
meso.save() meso.save()
if Microrregiao.objects.filter(codigo_ibge=cod_micro).exists(): if Microrregiao.objects.filter(codigo_ibge=cod_micro).exists():
micro = Microrregiao.objects.get(codigo_ibge=cod_micro) micro = Microrregiao.objects.get(codigo_ibge=cod_micro)
else: else:
micro = Microrregiao(codigo_ibge=cod_micro, mesorregiao=meso, nome=reg['nome_microrregiao']) micro = Microrregiao(
micro.nome = reg['nome_microrregiao'] codigo_ibge=cod_micro,
mesorregiao=meso,
nome=reg["nome_microrregiao"],
)
micro.nome = reg["nome_microrregiao"]
micro.save() micro.save()
municipio.microrregiao = micro municipio.microrregiao = micro
municipio.save() municipio.save()
self.stdout.write("Importação concluída. %s erros em %s linhas" % (erros, reader.line_num,)) self.stdout.write(
"Importação concluída. %s erros em %s linhas"
% (
erros,
reader.line_num,
)
)

452
sigi/apps/contatos/migrations/0001_initial.py

@ -8,128 +8,430 @@ import sigi.apps.utils
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('contenttypes', '0001_initial'), ("contenttypes", "0001_initial"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Contato', name="Contato",
fields=[ 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')), "id",
('nota', models.CharField(max_length=70, blank=True)), models.AutoField(
('email', models.EmailField(max_length=75, verbose_name='e-mail', blank=True)), verbose_name="ID",
('object_id', models.PositiveIntegerField()), serialize=False,
('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)), 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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'contato Interlegis', "verbose_name": "contato Interlegis",
'verbose_name_plural': 'contatos Interlegis', "verbose_name_plural": "contatos Interlegis",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Endereco', name="Endereco",
fields=[ 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')])), "id",
('logradouro', models.CharField(max_length=100)), models.AutoField(
('numero', models.CharField(max_length=15, blank=True)), verbose_name="ID",
('complemento', models.CharField(max_length=15, blank=True)), serialize=False,
('referencia', models.CharField(max_length=100, blank=True)), auto_created=True,
('bairro', models.CharField(max_length=100, blank=True)), primary_key=True,
('cep', models.CharField(help_text='Formato: <em>XXXXX-XXX</em>.', 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)), (
"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: <em>XXXXX-XXX</em>.",
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={ options={
'ordering': ('logradouro', 'numero'), "ordering": ("logradouro", "numero"),
'verbose_name': 'endere\xe7o', "verbose_name": "endere\xe7o",
'verbose_name_plural': 'endere\xe7os', "verbose_name_plural": "endere\xe7os",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Municipio', name="Municipio",
fields=[ 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_ibge",
('codigo_microrregiao', models.PositiveIntegerField(null=True, verbose_name='c\xf3digo microrregi\xe3o', blank=True)), models.PositiveIntegerField(
('codigo_tse', models.PositiveIntegerField(help_text='C\xf3digo do munic\xedpio segundo TSE.', unique=True, null=True, verbose_name='c\xf3digo TSE')), help_text="C\xf3digo do munic\xedpio segundo IBGE.",
('nome', models.CharField(max_length=50)), unique=True,
('search_text', sigi.apps.utils.SearchField(field_names=['nome', 'uf'], editable=False)), serialize=False,
('is_capital', models.BooleanField(default=False, verbose_name='capital')), verbose_name="c\xf3digo IBGE",
('populacao', models.PositiveIntegerField(verbose_name='popula\xe7\xe3o')), primary_key=True,
('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: <em>-20,464</em>.', null=True, max_digits=10, decimal_places=8, blank=True)), (
('longitude', models.DecimalField(help_text='Exemplo: <em>-45,426</em>.', null=True, max_digits=11, decimal_places=8, blank=True)), "codigo_mesorregiao",
('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)])), models.PositiveIntegerField(
('pib_total', models.DecimalField(null=True, verbose_name='PIB total', max_digits=18, decimal_places=3, blank=True)), null=True,
('pib_percapita', models.DecimalField(null=True, verbose_name='PIB per capita', max_digits=18, decimal_places=3, blank=True)), verbose_name="c\xf3digo mesorregi\xe3o",
('pib_ano', models.IntegerField(null=True, verbose_name='Ano de apura\xe7\xe3o do PIB', blank=True)), 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: <em>-20,464</em>.",
null=True,
max_digits=10,
decimal_places=8,
blank=True,
),
),
(
"longitude",
models.DecimalField(
help_text="Exemplo: <em>-45,426</em>.",
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={ options={
'ordering': ('nome', 'codigo_ibge'), "ordering": ("nome", "codigo_ibge"),
'verbose_name': 'munic\xedpio', "verbose_name": "munic\xedpio",
'verbose_name_plural': 'munic\xedpios', "verbose_name_plural": "munic\xedpios",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Telefone', name="Telefone",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('numero', models.CharField(help_text='Exemplo: <em>(31)8851-9898</em>.', max_length=64, verbose_name='n\xfamero')), "id",
('tipo', models.CharField(default='I', max_length=1, choices=[('F', 'Fixo'), ('M', 'M\xf3vel'), ('X', 'Fax'), ('I', 'Indefinido')])), models.AutoField(
('nota', models.CharField(max_length=70, null=True, blank=True)), verbose_name="ID",
('ult_alteracao', models.DateTimeField(auto_now=True, verbose_name='\xdaltima altera\xe7\xe3o', null=True)), serialize=False,
('object_id', models.PositiveIntegerField()), auto_created=True,
('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)), primary_key=True,
),
),
(
"numero",
models.CharField(
help_text="Exemplo: <em>(31)8851-9898</em>.",
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={ options={
'ordering': ('numero',), "ordering": ("numero",),
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='UnidadeFederativa', name="UnidadeFederativa",
fields=[ 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')), "codigo_ibge",
('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)), models.PositiveIntegerField(
('sigla', models.CharField(help_text='Exemplo: <em>MG</em>.', unique=True, max_length=2)), help_text="C\xf3digo do estado segundo IBGE.",
('regiao', models.CharField(max_length=2, verbose_name='regi\xe3o', choices=[('SL', 'Sul'), ('SD', 'Sudeste'), ('CO', 'Centro-Oeste'), ('NE', 'Nordeste'), ('NO', 'Norte')])), unique=True,
('populacao', models.PositiveIntegerField(verbose_name='popula\xe7\xe3o')), 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: <em>MG</em>.",
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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'Unidade Federativa', "verbose_name": "Unidade Federativa",
'verbose_name_plural': 'Unidades Federativas', "verbose_name_plural": "Unidades Federativas",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.AlterUniqueTogether( migrations.AlterUniqueTogether(
name='telefone', name="telefone",
unique_together=set([('numero', 'tipo')]), unique_together=set([("numero", "tipo")]),
), ),
migrations.AddField( migrations.AddField(
model_name='municipio', model_name="municipio",
name='uf', name="uf",
field=models.ForeignKey(verbose_name='UF', to='contatos.UnidadeFederativa', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="UF",
to="contatos.UnidadeFederativa",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='endereco', model_name="endereco",
name='municipio', name="municipio",
field=models.ForeignKey(verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True, on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="munic\xedpio",
blank=True,
to="contatos.Municipio",
null=True,
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='contato', model_name="contato",
name='municipio', name="municipio",
field=models.ForeignKey(verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True, on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="munic\xedpio",
blank=True,
to="contatos.Municipio",
null=True,
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
] ]

104
sigi/apps/contatos/migrations/0002_auto_20151104_0810.py

@ -8,52 +8,108 @@ import sigi.apps.utils
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('contatos', '0001_initial'), ("contatos", "0001_initial"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Mesorregiao', name="Mesorregiao",
fields=[ 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')), "codigo_ibge",
('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)), models.PositiveIntegerField(
('uf', models.ForeignKey(verbose_name='UF', to='contatos.UnidadeFederativa', on_delete=models.CASCADE)), 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={ options={
'ordering': ('uf', 'nome'), "ordering": ("uf", "nome"),
'verbose_name': 'Mesorregi\xe3o', "verbose_name": "Mesorregi\xe3o",
'verbose_name_plural': 'Mesorregi\xf5es', "verbose_name_plural": "Mesorregi\xf5es",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Microrregiao', name="Microrregiao",
fields=[ 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')), "codigo_ibge",
('search_text', sigi.apps.utils.SearchField(field_names=['nome'], editable=False)), models.PositiveIntegerField(
('mesorregiao', models.ForeignKey(to='contatos.Mesorregiao', on_delete=models.CASCADE)), 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={ options={
'ordering': ('mesorregiao', 'nome'), "ordering": ("mesorregiao", "nome"),
'verbose_name': 'Microrregi\xe3o', "verbose_name": "Microrregi\xe3o",
'verbose_name_plural': 'Microrregi\xf5es', "verbose_name_plural": "Microrregi\xf5es",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.RemoveField( migrations.RemoveField(
model_name='municipio', model_name="municipio",
name='codigo_mesorregiao', name="codigo_mesorregiao",
), ),
migrations.RemoveField( migrations.RemoveField(
model_name='municipio', model_name="municipio",
name='codigo_microrregiao', name="codigo_microrregiao",
), ),
migrations.AddField( migrations.AddField(
model_name='municipio', model_name="municipio",
name='microrregiao', name="microrregiao",
field=models.ForeignKey(verbose_name='Microrregi\xe3o', blank=True, to='contatos.Microrregiao', null=True, on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Microrregi\xe3o",
blank=True,
to="contatos.Microrregiao",
null=True,
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
] ]

48
sigi/apps/contatos/migrations/0003_auto_20210416_0841.py

@ -8,32 +8,54 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('contatos', '0002_auto_20151104_0810'), ("contatos", "0002_auto_20151104_0810"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='contato', model_name="contato",
name='municipio', name="municipio",
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='endereco', model_name="endereco",
name='municipio', name="municipio",
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='munic\xedpio', blank=True, to='contatos.Municipio', null=True), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='municipio', model_name="municipio",
name='microrregiao', name="microrregiao",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Microrregi\xe3o', blank=True, to='contatos.Microrregiao', null=True), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Microrregi\xe3o",
blank=True,
to="contatos.Microrregiao",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='municipio', model_name="municipio",
name='uf', name="uf",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='UF', to='contatos.UnidadeFederativa'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="UF",
to="contatos.UnidadeFederativa",
),
preserve_default=True, preserve_default=True,
), ),
] ]

26
sigi/apps/contatos/migrations/0004_auto_20210611_0946.py

@ -7,18 +7,32 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('contatos', '0003_auto_20210416_0841'), ("contatos", "0003_auto_20210416_0841"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='microrregiao', name="microrregiao",
options={'ordering': ('nome',), 'verbose_name': 'Microrregi\xe3o', 'verbose_name_plural': 'Microrregi\xf5es'}, options={
"ordering": ("nome",),
"verbose_name": "Microrregi\xe3o",
"verbose_name_plural": "Microrregi\xf5es",
},
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadefederativa', model_name="unidadefederativa",
name='regiao', name="regiao",
field=models.CharField(max_length=2, verbose_name='regi\xe3o', choices=[('CO', 'Centro-Oeste'), ('NE', 'Nordeste'), ('NO', 'Norte'), ('SD', 'Sudeste'), ('SL', 'Sul')]), 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, preserve_default=True,
), ),
] ]

290
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): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('contatos', '0004_auto_20210611_0946'), ("contatos", "0004_auto_20210611_0946"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='mesorregiao', name="mesorregiao",
options={'ordering': ('uf', 'nome'), 'verbose_name': ('mesorregião',), 'verbose_name_plural': 'mesorregiões'}, options={
"ordering": ("uf", "nome"),
"verbose_name": ("mesorregião",),
"verbose_name_plural": "mesorregiões",
},
), ),
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='microrregiao', name="microrregiao",
options={'ordering': ('nome',), 'verbose_name': 'microrregião', 'verbose_name_plural': 'microrregiões'}, options={
"ordering": ("nome",),
"verbose_name": "microrregião",
"verbose_name_plural": "microrregiões",
},
), ),
migrations.AlterField( migrations.AlterField(
model_name='contato', model_name="contato",
name='email', name="email",
field=models.EmailField(blank=True, max_length=254, verbose_name='e-mail'), field=models.EmailField(
blank=True, max_length=254, verbose_name="e-mail"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='contato', model_name="contato",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='endereco', model_name="endereco",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='endereco', model_name="endereco",
name='logradouro', name="logradouro",
field=models.CharField(max_length=100, verbose_name='logradouro'), field=models.CharField(max_length=100, verbose_name="logradouro"),
), ),
migrations.AlterField( migrations.AlterField(
model_name='endereco', model_name="endereco",
name='tipo', 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'), 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( migrations.AlterField(
model_name='mesorregiao', model_name="mesorregiao",
name='codigo_ibge', 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'), 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( migrations.AlterField(
model_name='mesorregiao', model_name="mesorregiao",
name='nome', name="nome",
field=models.CharField(max_length=100, verbose_name='nome mesorregião'), field=models.CharField(
max_length=100, verbose_name="nome mesorregião"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='mesorregiao', model_name="mesorregiao",
name='search_text', name="search_text",
field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']), field=sigi.apps.utils.SearchField(
editable=False, field_names=["nome"]
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='microrregiao', model_name="microrregiao",
name='codigo_ibge', 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'), 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( migrations.AlterField(
model_name='microrregiao', model_name="microrregiao",
name='mesorregiao', name="mesorregiao",
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contatos.mesorregiao', verbose_name='mesorregião'), field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="contatos.mesorregiao",
verbose_name="mesorregião",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='microrregiao', model_name="microrregiao",
name='nome', name="nome",
field=models.CharField(max_length=100, verbose_name='nome microrregião'), field=models.CharField(
max_length=100, verbose_name="nome microrregião"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='microrregiao', model_name="microrregiao",
name='search_text', name="search_text",
field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']), field=sigi.apps.utils.SearchField(
editable=False, field_names=["nome"]
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='municipio', model_name="municipio",
name='latitude', name="latitude",
field=models.DecimalField(blank=True, decimal_places=8, help_text='Exemplo: <em>-20,464</em>.', max_digits=10, null=True, verbose_name='latitude'), field=models.DecimalField(
blank=True,
decimal_places=8,
help_text="Exemplo: <em>-20,464</em>.",
max_digits=10,
null=True,
verbose_name="latitude",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='municipio', model_name="municipio",
name='longitude', name="longitude",
field=models.DecimalField(blank=True, decimal_places=8, help_text='Exemplo: <em>-45,426</em>.', max_digits=11, null=True, verbose_name='longitude'), field=models.DecimalField(
blank=True,
decimal_places=8,
help_text="Exemplo: <em>-45,426</em>.",
max_digits=11,
null=True,
verbose_name="longitude",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='municipio', model_name="municipio",
name='microrregiao', name="microrregiao",
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='contatos.microrregiao', verbose_name='microrregião'), field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
to="contatos.microrregiao",
verbose_name="microrregião",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='telefone', model_name="telefone",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='telefone', model_name="telefone",
name='tipo', name="tipo",
field=models.CharField(choices=[('F', 'Fixo'), ('M', 'Móvel'), ('X', 'Fax'), ('I', 'Indefinido')], default='I', max_length=1, verbose_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( migrations.AlterField(
model_name='telefone', model_name="telefone",
name='ult_alteracao', name="ult_alteracao",
field=models.DateTimeField(auto_now=True, null=True, verbose_name='última alteração'), field=models.DateTimeField(
auto_now=True, null=True, verbose_name="última alteração"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadefederativa', model_name="unidadefederativa",
name='nome', name="nome",
field=models.CharField(max_length=25, verbose_name='nome UF'), field=models.CharField(max_length=25, verbose_name="nome UF"),
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadefederativa', model_name="unidadefederativa",
name='regiao', name="regiao",
field=models.CharField(choices=[('CO', 'Centro-Oeste'), ('NE', 'Nordeste'), ('NO', 'Norte'), ('SD', 'Sudeste'), ('SL', 'Sul')], max_length=2, verbose_name='região'), field=models.CharField(
choices=[
("CO", "Centro-Oeste"),
("NE", "Nordeste"),
("NO", "Norte"),
("SD", "Sudeste"),
("SL", "Sul"),
],
max_length=2,
verbose_name="região",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadefederativa', model_name="unidadefederativa",
name='search_text', name="search_text",
field=sigi.apps.utils.SearchField(editable=False, field_names=['nome']), field=sigi.apps.utils.SearchField(
editable=False, field_names=["nome"]
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadefederativa', model_name="unidadefederativa",
name='sigla', name="sigla",
field=models.CharField(help_text='Exemplo: <em>MG</em>.', max_length=2, unique=True, verbose_name='sigla'), field=models.CharField(
help_text="Exemplo: <em>MG</em>.",
max_length=2,
unique=True,
verbose_name="sigla",
),
), ),
] ]

298
sigi/apps/contatos/models.py

@ -1,5 +1,7 @@
from django.contrib.contenttypes.fields import (GenericForeignKey, from django.contrib.contenttypes.fields import (
GenericRelation) GenericForeignKey,
GenericRelation,
)
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.core.validators import MaxValueValidator, MinValueValidator from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models from django.db import models
@ -9,200 +11,192 @@ from sigi.apps.utils import SearchField
class UnidadeFederativa(models.Model): class UnidadeFederativa(models.Model):
REGIAO_CHOICES = ( REGIAO_CHOICES = (
('CO', _('Centro-Oeste')), ("CO", _("Centro-Oeste")),
('NE', _('Nordeste')), ("NE", _("Nordeste")),
('NO', _('Norte')), ("NO", _("Norte")),
('SD', _('Sudeste')), ("SD", _("Sudeste")),
('SL', _('Sul')), ("SL", _("Sul")),
) )
codigo_ibge = models.PositiveIntegerField( codigo_ibge = models.PositiveIntegerField(
_('código IBGE'), _("código IBGE"),
primary_key=True, primary_key=True,
unique=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 # Campo de busca em caixa baixa sem acento
search_text = SearchField(field_names=['nome']) search_text = SearchField(field_names=["nome"])
sigla = models.CharField( sigla = models.CharField(
_('sigla'), _("sigla"),
max_length=2, max_length=2,
unique=True, unique=True,
help_text=_("Exemplo: <em>MG</em>."), help_text=_("Exemplo: <em>MG</em>."),
) )
regiao = models.CharField(_('região'), max_length=2, choices=REGIAO_CHOICES) regiao = models.CharField(_("região"), max_length=2, choices=REGIAO_CHOICES)
populacao = models.PositiveIntegerField(_('população')) populacao = models.PositiveIntegerField(_("população"))
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _('Unidade Federativa') verbose_name = _("Unidade Federativa")
verbose_name_plural = _('Unidades Federativas') verbose_name_plural = _("Unidades Federativas")
def __str__(self): def __str__(self):
return self.nome return self.nome
class Mesorregiao(models.Model): class Mesorregiao(models.Model):
codigo_ibge = models.PositiveIntegerField( codigo_ibge = models.PositiveIntegerField(
_('código IBGE'), _("código IBGE"),
primary_key=True, primary_key=True,
unique=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( uf = models.ForeignKey(
UnidadeFederativa, UnidadeFederativa, on_delete=models.CASCADE, verbose_name=_("UF")
on_delete=models.CASCADE,
verbose_name=_('UF')
) )
nome = models.CharField(_("nome mesorregião"), max_length=100) nome = models.CharField(_("nome mesorregião"), max_length=100)
# Campo de busca em caixa baixa sem acento # Campo de busca em caixa baixa sem acento
search_text = SearchField(field_names=['nome']) search_text = SearchField(field_names=["nome"])
class Meta: class Meta:
ordering = ('uf', 'nome',) ordering = (
verbose_name = _('mesorregião'), "uf",
verbose_name_plural = _('mesorregiões') "nome",
)
verbose_name = (_("mesorregião"),)
verbose_name_plural = _("mesorregiões")
def __str__(self): def __str__(self):
return self.nome return self.nome
class Microrregiao(models.Model): class Microrregiao(models.Model):
codigo_ibge = models.PositiveIntegerField( codigo_ibge = models.PositiveIntegerField(
_('código IBGE'), _("código IBGE"),
primary_key=True, primary_key=True,
unique=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 = models.ForeignKey(
Mesorregiao, Mesorregiao,
on_delete=models.CASCADE, on_delete=models.CASCADE,
verbose_name=_('mesorregião'), verbose_name=_("mesorregião"),
) )
nome = models.CharField(_("nome microrregião"), max_length=100) nome = models.CharField(_("nome microrregião"), max_length=100)
# Campo de busca em caixa baixa sem acento # Campo de busca em caixa baixa sem acento
search_text = SearchField(field_names=['nome']) search_text = SearchField(field_names=["nome"])
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _('microrregião') verbose_name = _("microrregião")
verbose_name_plural = _('microrregiões') verbose_name_plural = _("microrregiões")
def __str__(self): def __str__(self):
return f"{self.nome} ({self.mesorregiao.nome})" return f"{self.nome} ({self.mesorregiao.nome})"
class Municipio(models.Model): class Municipio(models.Model):
codigo_ibge = models.PositiveIntegerField( codigo_ibge = models.PositiveIntegerField(
_('código IBGE'), _("código IBGE"),
primary_key=True, primary_key=True,
unique=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 = models.ForeignKey(
Microrregiao, Microrregiao,
on_delete=models.PROTECT, on_delete=models.PROTECT,
verbose_name=_('microrregião'), verbose_name=_("microrregião"),
blank=True, blank=True,
null=True null=True,
) )
# codigo designado pelo Tribunal Superior Eleitoral # codigo designado pelo Tribunal Superior Eleitoral
codigo_tse = models.PositiveIntegerField( codigo_tse = models.PositiveIntegerField(
_('código TSE'), _("código TSE"),
unique=True, unique=True,
null=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) nome = models.CharField(max_length=50)
search_text = SearchField(field_names=[_('nome'), _('uf')]) search_text = SearchField(field_names=[_("nome"), _("uf")])
uf = models.ForeignKey( uf = models.ForeignKey(
UnidadeFederativa, UnidadeFederativa, on_delete=models.PROTECT, verbose_name=_("UF")
on_delete=models.PROTECT,
verbose_name=_('UF')
) )
# verdadeiro se o município é capital do estado # verdadeiro se o município é capital do estado
is_capital = models.BooleanField(_('capital'), default=False) is_capital = models.BooleanField(_("capital"), default=False)
populacao = models.PositiveIntegerField(_('população')) populacao = models.PositiveIntegerField(_("população"))
is_polo = models.BooleanField(_('pólo'), default=False) is_polo = models.BooleanField(_("pólo"), default=False)
data_criacao = models.DateField( data_criacao = models.DateField(
_('data de criação do município'), _("data de criação do município"), null=True, blank=True
null=True,
blank=True
) )
# posição geográfica do município # posição geográfica do município
latitude = models.DecimalField( latitude = models.DecimalField(
_('latitude'), _("latitude"),
max_digits=10, max_digits=10,
decimal_places=8, decimal_places=8,
null=True, null=True,
blank=True, blank=True,
help_text=_('Exemplo: <em>-20,464</em>.') help_text=_("Exemplo: <em>-20,464</em>."),
) )
longitude = models.DecimalField( longitude = models.DecimalField(
_('longitude'), _("longitude"),
max_digits=11, max_digits=11,
decimal_places=8, decimal_places=8,
null=True, null=True,
blank=True, blank=True,
help_text=_('Exemplo: <em>-45,426</em>.') help_text=_("Exemplo: <em>-45,426</em>."),
) )
idh = models.DecimalField( idh = models.DecimalField(
_('IDH'), _("IDH"),
help_text=_('Índice de desenvolvimento Humano'), help_text=_("Índice de desenvolvimento Humano"),
max_digits=4, max_digits=4,
decimal_places=3, decimal_places=3,
validators=[MinValueValidator(0), MaxValueValidator(1)] validators=[MinValueValidator(0), MaxValueValidator(1)],
) )
pib_total = models.DecimalField( pib_total = models.DecimalField(
_('PIB total'), _("PIB total"), max_digits=18, decimal_places=3, blank=True, null=True
max_digits=18,
decimal_places=3,
blank=True,
null=True
) )
pib_percapita = models.DecimalField( pib_percapita = models.DecimalField(
_('PIB per capita'), _("PIB per capita"),
max_digits=18, max_digits=18,
decimal_places=3, decimal_places=3,
blank=True, blank=True,
null=True null=True,
) )
pib_ano = models.IntegerField( pib_ano = models.IntegerField(
_('Ano de apuração do PIB'), _("Ano de apuração do PIB"), blank=True, null=True
blank=True,
null=True
) )
class Meta: class Meta:
ordering = ('nome', 'codigo_ibge') ordering = ("nome", "codigo_ibge")
verbose_name = _('município') verbose_name = _("município")
verbose_name_plural = _('municípios') verbose_name_plural = _("municípios")
def __str__(self): def __str__(self):
return f"{self.nome} - {self.uf}" return f"{self.nome} - {self.uf}"
class Telefone(models.Model): class Telefone(models.Model):
TELEFONE_CHOICES = ( TELEFONE_CHOICES = (
('F', _('Fixo')), ("F", _("Fixo")),
('M', _('Móvel')), ("M", _("Móvel")),
('X', _('Fax')), ("X", _("Fax")),
('I', _('Indefinido')), ("I", _("Indefinido")),
) )
numero = models.CharField( numero = models.CharField(
_('número'), _("número"),
max_length=64, max_length=64,
help_text=_('Exemplo: <em>(31)8851-9898</em>.'), help_text=_("Exemplo: <em>(31)8851-9898</em>."),
) )
tipo = models.CharField( tipo = models.CharField(
_('tipo'), _("tipo"), max_length=1, choices=TELEFONE_CHOICES, default="I"
max_length=1,
choices=TELEFONE_CHOICES,
default='I'
) )
nota = models.CharField(max_length=70, null=True, blank=True) nota = models.CharField(max_length=70, null=True, blank=True)
ult_alteracao = models.DateTimeField( ult_alteracao = models.DateTimeField(
_('última alteração'), _("última alteração"),
null=True, null=True,
blank=True, blank=True,
editable=False, editable=False,
auto_now=True auto_now=True,
) )
# guarda o tipo do objeto (classe) vinculado a esse registro # 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 # identificador do registro na classe vinculado a esse registro
object_id = models.PositiveIntegerField() object_id = models.PositiveIntegerField()
content_object = GenericForeignKey( content_object = GenericForeignKey(
'content_type', "content_type",
'object_id', "object_id",
) )
class Meta: class Meta:
ordering = ('numero',) ordering = ("numero",)
unique_together = ('numero', 'tipo') unique_together = ("numero", "tipo")
def __str__(self): def __str__(self):
return self.numero return self.numero
class Contato(models.Model): 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) 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) telefones = GenericRelation(Telefone)
municipio = models.ForeignKey( municipio = models.ForeignKey(
Municipio, Municipio,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
verbose_name=_('município'), verbose_name=_("município"),
blank=True, blank=True,
null=True, null=True,
) )
@ -238,70 +233,71 @@ class Contato(models.Model):
# identificador do registro na classe vinculado a esse registro # identificador do registro na classe vinculado a esse registro
object_id = models.PositiveIntegerField() object_id = models.PositiveIntegerField()
content_object = GenericForeignKey( content_object = GenericForeignKey(
'content_type', "content_type",
'object_id', "object_id",
) )
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _('contato Interlegis') verbose_name = _("contato Interlegis")
verbose_name_plural = _('contatos Interlegis') verbose_name_plural = _("contatos Interlegis")
def __str__(self): def __str__(self):
return self.nome return self.nome
class Endereco(models.Model): class Endereco(models.Model):
TIPO_CHOICES = ( TIPO_CHOICES = (
('aeroporto', _('Aeroporto')), ("aeroporto", _("Aeroporto")),
('alameda', _('Alameda')), ("alameda", _("Alameda")),
('area', _('Área')), ("area", _("Área")),
('avenida', _('Avenida')), ("avenida", _("Avenida")),
('campo', _('Campo')), ("campo", _("Campo")),
('chacara', _('Chácara')), ("chacara", _("Chácara")),
('colonia', _('Colônia')), ("colonia", _("Colônia")),
('condominio', _('Condomínio')), ("condominio", _("Condomínio")),
('conjunto', _('Conjunto')), ("conjunto", _("Conjunto")),
('distrito', _('Distrito')), ("distrito", _("Distrito")),
('esplanada', _('Esplanada')), ("esplanada", _("Esplanada")),
('estacao', _('Estação')), ("estacao", _("Estação")),
('estrada', _('Estrada')), ("estrada", _("Estrada")),
('favela', _('Favela')), ("favela", _("Favela")),
('fazenda', _('Fazenda')), ("fazenda", _("Fazenda")),
('feira', _('Feira')), ("feira", _("Feira")),
('jardim', _('Jardim')), ("jardim", _("Jardim")),
('ladeira', _('Ladeira')), ("ladeira", _("Ladeira")),
('lago', _('Lago')), ("lago", _("Lago")),
('lagoa', _('Lagoa')), ("lagoa", _("Lagoa")),
('largo', _('Largo')), ("largo", _("Largo")),
('loteamento', _('Loteamento')), ("loteamento", _("Loteamento")),
('morro', _('Morro')), ("morro", _("Morro")),
('nucleo', _('Núcleo')), ("nucleo", _("Núcleo")),
('parque', _('Parque')), ("parque", _("Parque")),
('passarela', _('Passarela')), ("passarela", _("Passarela")),
('patio', _('Pátio')), ("patio", _("Pátio")),
('praca', _('Praça')), ("praca", _("Praça")),
('quadra', _('Quadra')), ("quadra", _("Quadra")),
('recanto', _('Recanto')), ("recanto", _("Recanto")),
('residencial', _('Residencial')), ("residencial", _("Residencial")),
('rodovia', _('Rodovia')), ("rodovia", _("Rodovia")),
('rua', _('Rua')), ("rua", _("Rua")),
('setor', _('Setor')), ("setor", _("Setor")),
('sitio', _('Sítio')), ("sitio", _("Sítio")),
('travessa', _('Travessa')), ("travessa", _("Travessa")),
('trecho', _('Trecho')), ("trecho", _("Trecho")),
('trevo', _('Trevo')), ("trevo", _("Trevo")),
('vale', _('Vale')), ("vale", _("Vale")),
('vereda', _('Vereda')), ("vereda", _("Vereda")),
('via', _('Via')), ("via", _("Via")),
('viaduto', _('Viaduto')), ("viaduto", _("Viaduto")),
('viela', _('Viela')), ("viela", _("Viela")),
('vila', _('Vila')), ("vila", _("Vila")),
('outro', _('Outro')), ("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 = models.CharField(
_('logradouro'), _("logradouro"),
max_length=100, max_length=100,
) )
numero = models.CharField(max_length=15, blank=True) numero = models.CharField(max_length=15, blank=True)
@ -309,16 +305,16 @@ class Endereco(models.Model):
referencia = models.CharField(max_length=100, blank=True) referencia = models.CharField(max_length=100, blank=True)
bairro = models.CharField(max_length=100, blank=True) bairro = models.CharField(max_length=100, blank=True)
cep = models.CharField( cep = models.CharField(
_('CEP'), _("CEP"),
max_length=9, max_length=9,
blank=True, blank=True,
null=True, null=True,
help_text=_("Formato: <em>XXXXX-XXX</em>.") help_text=_("Formato: <em>XXXXX-XXX</em>."),
) )
municipio = models.ForeignKey( municipio = models.ForeignKey(
Municipio, Municipio,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
verbose_name=_('município'), verbose_name=_("município"),
blank=True, blank=True,
null=True, null=True,
) )
@ -327,15 +323,17 @@ class Endereco(models.Model):
# identificador do registro na classe vinculado a esse registro # identificador do registro na classe vinculado a esse registro
object_id = models.PositiveIntegerField() object_id = models.PositiveIntegerField()
content_object = GenericForeignKey( content_object = GenericForeignKey(
'content_type', "content_type",
'object_id', "object_id",
) )
class Meta: class Meta:
ordering = ('logradouro', 'numero') ordering = ("logradouro", "numero")
verbose_name = _('endereço') verbose_name = _("endereço")
verbose_name_plural = _('endereços') verbose_name_plural = _("endereços")
def __str__(self): def __str__(self):
return (f"{self.tipo} {self.logradouro}, {self.numero}" return (
f"{self.complemento} - {self.bairro}") f"{self.tipo} {self.logradouro}, {self.numero}"
f"{self.complemento} - {self.bairro}"
)

279
sigi/apps/convenios/admin.py

@ -2,10 +2,16 @@ from django.contrib import admin
from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from sigi.apps.convenios.models import (Projeto, StatusConvenio, from sigi.apps.convenios.models import (
TipoSolicitacao, Convenio, Projeto,
EquipamentoPrevisto, Anexo, Tramitacao, StatusConvenio,
Gescon) TipoSolicitacao,
Convenio,
EquipamentoPrevisto,
Anexo,
Tramitacao,
Gescon,
)
from sigi.apps.utils import queryset_ascii from sigi.apps.utils import queryset_ascii
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
from sigi.apps.casas.admin import ConveniosInline, GerentesInterlegisFilter 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 django_weasyprint.views import WeasyTemplateResponse
from sigi.apps.utils.filters import DateRangeFilter from sigi.apps.utils.filters import DateRangeFilter
class ConvenioExportResourse(LabeledResourse): class ConvenioExportResourse(LabeledResourse):
class Meta: class Meta:
model = Convenio model = Convenio
fields = ('num_processo_sf', 'num_convenio', 'projeto__nome', fields = (
'casa_legislativa__nome', 'casa_legislativa__municipio__nome', "num_processo_sf",
'casa_legislativa__municipio__uf__sigla', 'data_sigi', "num_convenio",
'data_sigad', 'data_adesao', 'data_retorno_assinatura', "projeto__nome",
'data_solicitacao', 'atualizacao_gescon', 'observacao_gescon', "casa_legislativa__nome",
'tipo_solicitacao__nome', 'status__nome', "casa_legislativa__municipio__nome",
'acompanha__nome_completo', 'servidor_gestao__nome_completo', "casa_legislativa__municipio__uf__sigla",
'observacao') "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 export_order = fields
class AnexosInline(admin.TabularInline): class AnexosInline(admin.TabularInline):
model = Anexo model = Anexo
extra = 2 extra = 2
exclude = ['data_pub', ] exclude = [
"data_pub",
]
class AnexoAdmin(admin.ModelAdmin): class AnexoAdmin(admin.ModelAdmin):
date_hierarchy = 'data_pub' date_hierarchy = "data_pub"
exclude = ['data_pub', ] exclude = [
list_display = ('arquivo', 'descricao', 'data_pub', 'convenio') "data_pub",
raw_id_fields = ('convenio',) ]
search_fields = ('descricao', 'convenio__id', 'arquivo', list_display = ("arquivo", "descricao", "data_pub", "convenio")
'convenio__casa_legislativa__nome') raw_id_fields = ("convenio",)
search_fields = (
"descricao",
"convenio__id",
"arquivo",
"convenio__casa_legislativa__nome",
)
class AcompanhaFilter(admin.filters.RelatedFieldListFilter): class AcompanhaFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(AcompanhaFilter, self).__init__(*args, **kwargs) super(AcompanhaFilter, self).__init__(*args, **kwargs)
servidores = Servidor.objects.filter( servidores = (
convenio__isnull=False).order_by('nome_completo').distinct() Servidor.objects.filter(convenio__isnull=False)
.order_by("nome_completo")
.distinct()
)
self.lookup_choices = [(x.id, x) for x in servidores] self.lookup_choices = [(x.id, x) for x in servidores]
@admin.register(Convenio) @admin.register(Convenio)
class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin): class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
fieldsets = ( fieldsets = (
(None, (
{'fields': ('casa_legislativa', 'num_processo_sf', 'num_convenio', None,
'projeto', 'data_sigi',)} {
"fields": (
"casa_legislativa",
"num_processo_sf",
"num_convenio",
"projeto",
"data_sigi",
)
},
), ),
(_("Acompanhamento no gabinete"), (
{'fields': ('data_solicitacao', 'data_sigad', 'observacao',)} _("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', _("Datas"),
'data_pub_diario',)} {
"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', readonly_fields = (
'link_gescon') "data_sigi",
"atualizacao_gescon",
"observacao_gescon",
"link_gescon",
)
inlines = (AnexosInline,) inlines = (AnexosInline,)
list_display = ('num_convenio', 'projeto','casa_legislativa', 'get_uf', list_display = (
'status_convenio', 'link_sigad', 'data_retorno_assinatura', "num_convenio",
'data_termino_vigencia',) "projeto",
list_display_links = ('num_convenio', 'casa_legislativa',) "casa_legislativa",
"get_uf",
"status_convenio",
"link_sigad",
"data_retorno_assinatura",
"data_termino_vigencia",
)
list_display_links = (
"num_convenio",
"casa_legislativa",
)
list_filter = ( list_filter = (
('data_retorno_assinatura', DateRangeFilter), ("data_retorno_assinatura", DateRangeFilter),
('data_sigi', DateRangeFilter), ('data_solicitacao', DateRangeFilter), ("data_sigi", DateRangeFilter),
('data_sigad', DateRangeFilter), ("data_solicitacao", DateRangeFilter),
('casa_legislativa__gerentes_interlegis', GerentesInterlegisFilter), ("data_sigad", DateRangeFilter),
'projeto', 'casa_legislativa__tipo', 'conveniada','equipada', ("casa_legislativa__gerentes_interlegis", GerentesInterlegisFilter),
'casa_legislativa__municipio__uf', "projeto",
) "casa_legislativa__tipo",
ordering = ('casa_legislativa', '-data_retorno_assinatura') "conveniada",
raw_id_fields = ('casa_legislativa',) "equipada",
"casa_legislativa__municipio__uf",
)
ordering = ("casa_legislativa", "-data_retorno_assinatura")
raw_id_fields = ("casa_legislativa",)
get_queryset = queryset_ascii get_queryset = queryset_ascii
search_fields = ('id', 'casa_legislativa__search_text', search_fields = (
'casa_legislativa__sigla', 'num_processo_sf', "id",
'num_convenio') "casa_legislativa__search_text",
"casa_legislativa__sigla",
"num_processo_sf",
"num_convenio",
)
resource_class = ConvenioExportResourse resource_class = ConvenioExportResourse
reports = [ reports = [
'report_convenios', "report_convenios",
'report_convenios_camaras', "report_convenios_camaras",
'report_convenios_assembleia', "report_convenios_assembleia",
] ]
def get_queryset(self, request): def get_queryset(self, request):
@ -101,8 +191,9 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
def get_uf(self, obj): def get_uf(self, obj):
return obj.casa_legislativa.municipio.uf.sigla 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): def status_convenio(self, obj):
if obj.pk is None: if obj.pk is None:
@ -118,12 +209,14 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
else: else:
label = r"info" label = r"info"
return mark_safe(f'<p class="label label-{label}">{status}</p>') return mark_safe(f'<p class="label label-{label}">{status}</p>')
status_convenio.short_description = _("Status do convênio") status_convenio.short_description = _("Status do convênio")
def link_sigad(self, obj): def link_sigad(self, obj):
if obj.pk is None: if obj.pk is None:
return "" return ""
return mark_safe(obj.get_sigad_url()) return mark_safe(obj.get_sigad_url())
link_sigad.short_description = _("Processo no Senado") link_sigad.short_description = _("Processo no Senado")
def link_gescon(self, obj): def link_gescon(self, obj):
@ -133,53 +226,63 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
f"<a href='https://adm.senado.gov.br/gestao-contratos/api/" f"<a href='https://adm.senado.gov.br/gestao-contratos/api/"
f"contratos/buscaTexto/{obj.id_contrato_gescon}'>" f"contratos/buscaTexto/{obj.id_contrato_gescon}'>"
f"https://adm.senado.gov.br/gestao-contratos/api/" f"https://adm.senado.gov.br/gestao-contratos/api/"
f"{obj.id_contrato_gescon}</a>") f"{obj.id_contrato_gescon}</a>"
)
link_gescon.short_description = _("Download MINUTA ASSINADA do Gescon") link_gescon.short_description = _("Download MINUTA ASSINADA do Gescon")
def report_convenios(self, request): def report_convenios(self, request):
context = { context = {
'convenios': self.get_queryset(request), "convenios": self.get_queryset(request),
'title': _('Relatório de convenios'), "title": _("Relatório de convenios"),
} }
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename='relatorio_convenios.pdf', filename="relatorio_convenios.pdf",
request=request, request=request,
template="convenios/convenios_report.html", template="convenios/convenios_report.html",
context=context, 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): def report_convenios_camaras(self, request):
context = { context = {
'convenios': self.get_queryset(request).filter(casa_legislativa__tipo__legislativo = False), "convenios": self.get_queryset(request).filter(
'title': _('Relatório de convenios de camaras municipais'), casa_legislativa__tipo__legislativo=False
),
"title": _("Relatório de convenios de camaras municipais"),
} }
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename='relatorio_convenios.pdf', filename="relatorio_convenios.pdf",
request=request, request=request,
template="convenios/convenios_report.html", template="convenios/convenios_report.html",
context=context, 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): def report_convenios_assembleia(self, request):
context = { context = {
'convenios': self.get_queryset(request).filter(casa_legislativa__tipo__legislativo = True), "convenios": self.get_queryset(request).filter(
'title': _('Relatório de convenios de assembleias legislativas'), casa_legislativa__tipo__legislativo=True
),
"title": _("Relatório de convenios de assembleias legislativas"),
} }
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename='relatorio_convenios.pdf', filename="relatorio_convenios.pdf",
request=request, request=request,
template="convenios/convenios_report.html", template="convenios/convenios_report.html",
context=context, 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): # def relatorio(self, request, queryset):
# # queryset.order_by('casa_legislativa__municipio__uf') # # queryset.order_by('casa_legislativa__municipio__uf')
@ -206,23 +309,35 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin):
def get_actions(self, request): def get_actions(self, request):
actions = super(ConvenioAdmin, self).get_actions(request) actions = super(ConvenioAdmin, self).get_actions(request)
if 'delete_selected' in actions: if "delete_selected" in actions:
del actions['delete_selected'] del actions["delete_selected"]
return actions return actions
@admin.register(EquipamentoPrevisto) @admin.register(EquipamentoPrevisto)
class EquipamentoPrevistoAdmin(admin.ModelAdmin): class EquipamentoPrevistoAdmin(admin.ModelAdmin):
list_display = ('convenio', 'equipamento', 'quantidade') list_display = ("convenio", "equipamento", "quantidade")
list_display_links = ('convenio', 'equipamento') list_display_links = ("convenio", "equipamento")
ordering = ('convenio', 'equipamento') ordering = ("convenio", "equipamento")
raw_id_fields = ('convenio', 'equipamento') raw_id_fields = ("convenio", "equipamento")
search_fields = ('convenio__id', 'equipamento__fabricante__nome', search_fields = (
'equipamento__modelo__modelo', 'equipamento__modelo__tipo__tipo') "convenio__id",
"equipamento__fabricante__nome",
"equipamento__modelo__modelo",
"equipamento__modelo__tipo__tipo",
)
@admin.register(Gescon) @admin.register(Gescon)
class GesconAdmin(admin.ModelAdmin): class GesconAdmin(admin.ModelAdmin):
list_display = ('url_gescon', 'email',) list_display = (
exclude = ['ultima_importacao',] "url_gescon",
"email",
)
exclude = [
"ultima_importacao",
]
admin.site.register(Projeto) admin.site.register(Projeto)
admin.site.register(StatusConvenio) admin.site.register(StatusConvenio)

5
sigi/apps/convenios/apps.py

@ -1,6 +1,7 @@
from django.apps import AppConfig from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class ConveniosConfig(AppConfig): class ConveniosConfig(AppConfig):
name = 'sigi.apps.convenios' name = "sigi.apps.convenios"
verbose_name = _('convênios') verbose_name = _("convênios")

312
sigi/apps/convenios/migrations/0001_initial.py

@ -8,116 +8,304 @@ import sigi.apps.utils
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('inventario', '__first__'), ("inventario", "__first__"),
('casas', '0001_initial'), ("casas", "0001_initial"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Anexo', name="Anexo",
fields=[ 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')), "id",
('descricao', models.CharField(max_length='70', verbose_name='descri\xe7\xe3o')), models.AutoField(
('data_pub', models.DateTimeField(default=datetime.datetime.now, verbose_name='data da publica\xe7\xe3o do anexo')), 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={ options={
'ordering': ('-data_pub',), "ordering": ("-data_pub",),
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Convenio', name="Convenio",
fields=[ 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)), "id",
('num_processo_sf', models.CharField(help_text='Formatos:<br/>Antigo: <em>XXXXXX/XX-X</em>.<br/><em>SIGAD: XXXXX.XXXXXX/XXXX-XX</em>', max_length=20, verbose_name='n\xfamero do processo SF (Senado Federal)', blank=True)), models.AutoField(
('num_convenio', models.CharField(max_length=10, verbose_name='n\xfamero do conv\xeanio', blank=True)), verbose_name="ID",
('data_adesao', models.DateField(null=True, verbose_name='Aderidas', blank=True)), serialize=False,
('data_retorno_assinatura', models.DateField(help_text='Conv\xeanio firmado.', null=True, verbose_name='Conveniadas', blank=True)), auto_created=True,
('data_pub_diario', models.DateField(null=True, verbose_name='data da publica\xe7\xe3o no Di\xe1rio Oficial', blank=True)), primary_key=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)), "search_text",
('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)), sigi.apps.utils.SearchField(
('observacao', models.CharField(max_length=100, null=True, blank=True)), field_names=["casa_legislativa"], editable=False
('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)), (
"num_processo_sf",
models.CharField(
help_text="Formatos:<br/>Antigo: <em>XXXXXX/XX-X</em>.<br/><em>SIGAD: XXXXX.XXXXXX/XXXX-XX</em>",
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={ options={
'ordering': ('id',), "ordering": ("id",),
'get_latest_by': 'id', "get_latest_by": "id",
'verbose_name': 'conv\xeanio', "verbose_name": "conv\xeanio",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='EquipamentoPrevisto', name="EquipamentoPrevisto",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('quantidade', models.PositiveSmallIntegerField(default=1)), "id",
('convenio', models.ForeignKey(verbose_name='conv\xeanio', to='convenios.Convenio', on_delete=models.CASCADE)), models.AutoField(
('equipamento', models.ForeignKey(to='inventario.Equipamento', on_delete=models.CASCADE)), 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={ options={
'verbose_name': 'equipamento previsto', "verbose_name": "equipamento previsto",
'verbose_name_plural': 'equipamentos previstos', "verbose_name_plural": "equipamentos previstos",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Projeto', name="Projeto",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('nome', models.CharField(max_length=50)), "id",
('sigla', models.CharField(max_length=10)), 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,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Tramitacao', name="Tramitacao",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('data', models.DateField()), "id",
('observacao', models.CharField(max_length='512', null=True, verbose_name='observa\xe7\xe3o', blank=True)), models.AutoField(
('convenio', models.ForeignKey(verbose_name='conv\xeanio', to='convenios.Convenio', on_delete=models.CASCADE)), 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={ options={
'verbose_name_plural': 'Tramita\xe7\xf5es', "verbose_name_plural": "Tramita\xe7\xf5es",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='UnidadeAdministrativa', name="UnidadeAdministrativa",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('sigla', models.CharField(max_length='10')), "id",
('nome', models.CharField(max_length='100')), 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,), bases=(models.Model,),
), ),
migrations.AddField( migrations.AddField(
model_name='tramitacao', model_name="tramitacao",
name='unid_admin', name="unid_admin",
field=models.ForeignKey(verbose_name='Unidade Administrativa', to='convenios.UnidadeAdministrativa', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Unidade Administrativa",
to="convenios.UnidadeAdministrativa",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='projeto', name="projeto",
field=models.ForeignKey(to='convenios.Projeto', on_delete=models.CASCADE), field=models.ForeignKey(
to="convenios.Projeto", on_delete=models.CASCADE
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='anexo', model_name="anexo",
name='convenio', name="convenio",
field=models.ForeignKey(verbose_name='conv\xeanio', to='convenios.Convenio', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="conv\xeanio",
to="convenios.Convenio",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
] ]

13
sigi/apps/convenios/migrations/0002_convenio_duracao.py

@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0001_initial'), ("convenios", "0001_initial"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='duracao', 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), 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, preserve_default=True,
), ),
] ]

14
sigi/apps/convenios/migrations/0003_auto_20210406_1945.py

@ -6,15 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0002_convenio_duracao'), ("convenios", "0002_convenio_duracao"),
('casas', '0014_auto_20210406_1945'), ("casas", "0014_auto_20210406_1945"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='casa_legislativa', name="casa_legislativa",
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Casa Legislativa",
to="casas.Orgao",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
] ]

114
sigi/apps/convenios/migrations/0004_auto_20210407_1928.py

@ -7,71 +7,119 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0001_initial'), ("servidores", "0001_initial"),
('convenios', '0003_auto_20210406_1945'), ("convenios", "0003_auto_20210406_1945"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='StatusConvenio', name="StatusConvenio",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('nome', models.CharField(max_length=100)), "id",
('cancela', models.BooleanField(default=False, verbose_name='Cancela o conv\xeanio')), 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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'Estado de convenios', "verbose_name": "Estado de convenios",
'verbose_name_plural': 'Estados de convenios', "verbose_name_plural": "Estados de convenios",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='acompanha', name="acompanha",
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='acompanhado por', blank=True, to='servidores.Servidor', null=True), 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, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='status', name="status",
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='estado atual', blank=True, to='convenios.StatusConvenio', null=True), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='casa_legislativa', name="casa_legislativa",
field=models.ForeignKey(verbose_name='\xf3rg\xe3o conveniado', to='casas.Orgao', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="\xf3rg\xe3o conveniado",
to="casas.Orgao",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='data_adesao', name="data_adesao",
field=models.DateField(null=True, verbose_name='aderidas', blank=True), field=models.DateField(
null=True, verbose_name="aderidas", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='data_retorno_assinatura', name="data_retorno_assinatura",
field=models.DateField(help_text='Conv\xeanio firmado.', null=True, verbose_name='conveniadas', blank=True), field=models.DateField(
help_text="Conv\xeanio firmado.",
null=True,
verbose_name="conveniadas",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='data_termo_aceite', name="data_termo_aceite",
field=models.DateField(help_text='Equipamentos recebidos.', null=True, verbose_name='equipadas', blank=True), field=models.DateField(
help_text="Equipamentos recebidos.",
null=True,
verbose_name="equipadas",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='duracao', 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), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='observacao', name="observacao",
field=models.TextField(null=True, verbose_name='observa\xe7\xf5es', blank=True), field=models.TextField(
null=True, verbose_name="observa\xe7\xf5es", blank=True
),
preserve_default=True, preserve_default=True,
), ),
] ]

20
sigi/apps/convenios/migrations/0005_auto_20210409_0842.py

@ -6,20 +6,26 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0004_auto_20210407_1928'), ("convenios", "0004_auto_20210407_1928"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='data_sigad', name="data_sigad",
field=models.DateField(null=True, verbose_name='data de cadastro no SIGAD', blank=True), field=models.DateField(
null=True, verbose_name="data de cadastro no SIGAD", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='data_sigi', name="data_sigi",
field=models.DateField(auto_now_add=True, verbose_name='data de cadastro no SIGI', null=True), field=models.DateField(
auto_now_add=True,
verbose_name="data de cadastro no SIGI",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

31
sigi/apps/convenios/migrations/0006_auto_20210416_0841.py

@ -7,26 +7,37 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0005_auto_20210409_0842'), ("convenios", "0005_auto_20210409_0842"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='casa_legislativa', name="casa_legislativa",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='\xf3rg\xe3o conveniado', to='casas.Orgao'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="\xf3rg\xe3o conveniado",
to="casas.Orgao",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='projeto', name="projeto",
field=models.ForeignKey(to='convenios.Projeto', on_delete=django.db.models.deletion.PROTECT), field=models.ForeignKey(
to="convenios.Projeto",
on_delete=django.db.models.deletion.PROTECT,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='tramitacao', model_name="tramitacao",
name='unid_admin', name="unid_admin",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Unidade Administrativa', to='convenios.UnidadeAdministrativa'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Unidade Administrativa",
to="convenios.UnidadeAdministrativa",
),
preserve_default=True, preserve_default=True,
), ),
] ]

44
sigi/apps/convenios/migrations/0007_auto_20210416_0918.py

@ -7,33 +7,51 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0006_auto_20210416_0841'), ("convenios", "0006_auto_20210416_0841"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='TipoSolicitacao', name="TipoSolicitacao",
fields=[ 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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'tipo de solicita\xe7\xe3o', "verbose_name": "tipo de solicita\xe7\xe3o",
'verbose_name_plural': 'Tipos de solicita\xe7\xe3o', "verbose_name_plural": "Tipos de solicita\xe7\xe3o",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='data_solicitacao', name="data_solicitacao",
field=models.DateField(null=True, verbose_name='data do e-mail de solicita\xe7\xe3o', blank=True), field=models.DateField(
null=True,
verbose_name="data do e-mail de solicita\xe7\xe3o",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='tipo_solicitacao', 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), 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, preserve_default=True,
), ),
] ]

42
sigi/apps/convenios/migrations/0008_auto_20210422_1907.py

@ -7,27 +7,47 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0004_auto_20210422_1907'), ("servidores", "0004_auto_20210422_1907"),
('convenios', '0007_auto_20210416_0918'), ("convenios", "0007_auto_20210416_0918"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='servico_gestao', 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), 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, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='servidor_gestao', 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), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='acompanha', 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), 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, preserve_default=True,
), ),
] ]

6
sigi/apps/convenios/migrations/0009_auto_20210611_0946.py

@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0008_auto_20210422_1907'), ("convenios", "0008_auto_20210422_1907"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='projeto', name="projeto",
options={'ordering': ('nome',)}, options={"ordering": ("nome",)},
), ),
] ]

13
sigi/apps/convenios/migrations/0010_auto_20210819_0833.py

@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0009_auto_20210611_0946'), ("convenios", "0009_auto_20210611_0946"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='data_retorno_assinatura', name="data_retorno_assinatura",
field=models.DateField(help_text='Conv\xeanio firmado.', null=True, verbose_name='data in\xedcio vig\xeancia', blank=True), field=models.DateField(
help_text="Conv\xeanio firmado.",
null=True,
verbose_name="data in\xedcio vig\xeancia",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

13
sigi/apps/convenios/migrations/0011_convenio_data_termino_vigencia.py

@ -6,14 +6,19 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0010_auto_20210819_0833'), ("convenios", "0010_auto_20210819_0833"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='data_termino_vigencia', 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), 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, preserve_default=True,
), ),
] ]

8
sigi/apps/convenios/migrations/0012_auto_20210831_0844.py

@ -2,11 +2,12 @@ from __future__ import unicode_literals
from datetime import date from datetime import date
from django.db import models, migrations from django.db import models, migrations
def migra_data_termino_vigencia(apps, schema_editor): 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(): 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 continue
ano = c.data_retorno_assinatura.year + int(c.duracao / 12) ano = c.data_retorno_assinatura.year + int(c.duracao / 12)
@ -26,10 +27,11 @@ def migra_data_termino_vigencia(apps, schema_editor):
c.data_termino_vigencia = data_fim c.data_termino_vigencia = data_fim
c.save() c.save()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0011_convenio_data_termino_vigencia'), ("convenios", "0011_convenio_data_termino_vigencia"),
] ]
operations = [ operations = [

6
sigi/apps/convenios/migrations/0013_remove_convenio_duracao.py

@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0012_auto_20210831_0844'), ("convenios", "0012_auto_20210831_0844"),
] ]
operations = [ operations = [
migrations.RemoveField( migrations.RemoveField(
model_name='convenio', model_name="convenio",
name='duracao', name="duracao",
), ),
] ]

62
sigi/apps/convenios/migrations/0014_gescon.py

@ -6,23 +6,65 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0013_remove_convenio_duracao'), ("convenios", "0013_remove_convenio_duracao"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Gescon', name="Gescon",
fields=[ 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}.<br/><strong>Por exemplo:</strong> https://adm.senado.gov.br/gestao-contratos/api/contratos/busca?especie=<strong>{s}</strong>', verbose_name='Webservice Gescon')), "id",
('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')), models.AutoField(
('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. <ul><li>Informe uma palavra por linha.</li><li>Ocorrendo qualquer uma das palavras, o contrato ser\xe1 importado.</li></ul>', verbose_name='Palavras de filtro')), verbose_name="ID",
('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')), serialize=False,
('ultima_importacao', models.TextField(verbose_name='Resultado da \xfaltima importa\xe7\xe3o', blank=True)), 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}.<br/><strong>Por exemplo:</strong> https://adm.senado.gov.br/gestao-contratos/api/contratos/busca?especie=<strong>{s}</strong>",
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. <ul><li>Informe uma palavra por linha.</li><li>Ocorrendo qualquer uma das palavras, o contrato ser\xe1 importado.</li></ul>",
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={ options={
'verbose_name': 'Configura\xe7\xe3o do Gescon', "verbose_name": "Configura\xe7\xe3o do Gescon",
'verbose_name_plural': 'Configura\xe7\xf5es do Gescon', "verbose_name_plural": "Configura\xe7\xf5es do Gescon",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),

6
sigi/apps/convenios/migrations/0015_remove_convenio_search_text.py

@ -6,12 +6,12 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0014_gescon'), ("convenios", "0014_gescon"),
] ]
operations = [ operations = [
migrations.RemoveField( migrations.RemoveField(
model_name='convenio', model_name="convenio",
name='search_text', name="search_text",
), ),
] ]

21
sigi/apps/convenios/migrations/0016_auto_20210909_0732.py

@ -6,20 +6,27 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0015_remove_convenio_search_text'), ("convenios", "0015_remove_convenio_search_text"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='atualizacao_gescon', name="atualizacao_gescon",
field=models.DateTimeField(null=True, verbose_name='Data de atualiza\xe7\xe3o pelo Gescon', blank=True), field=models.DateTimeField(
null=True,
verbose_name="Data de atualiza\xe7\xe3o pelo Gescon",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='observacao_gescon', name="observacao_gescon",
field=models.TextField(verbose_name='Observa\xe7\xf5es da atualiza\xe7\xe3o do Gescon', blank=True), field=models.TextField(
verbose_name="Observa\xe7\xf5es da atualiza\xe7\xe3o do Gescon",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

14
sigi/apps/convenios/migrations/0017_convenio_id_contrato_gescon.py

@ -6,14 +6,20 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0016_auto_20210909_0732'), ("convenios", "0016_auto_20210909_0732"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='convenio', model_name="convenio",
name='id_contrato_gescon', name="id_contrato_gescon",
field=models.CharField(default='', verbose_name='ID do contrato no Gescon', max_length=20, editable=False, blank=True), field=models.CharField(
default="",
verbose_name="ID do contrato no Gescon",
max_length=20,
editable=False,
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

12
sigi/apps/convenios/migrations/0018_auto_20211208_1256.py

@ -7,14 +7,18 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0017_convenio_id_contrato_gescon'), ("convenios", "0017_convenio_id_contrato_gescon"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='projeto', name="projeto",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Tipo de Convenio', to='convenios.Projeto'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Tipo de Convenio",
to="convenios.Projeto",
),
preserve_default=True, preserve_default=True,
), ),
] ]

153
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): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0018_auto_20211208_1256'), ("convenios", "0018_auto_20211208_1256"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='anexo', model_name="anexo",
name='arquivo', name="arquivo",
field=models.FileField(max_length=500, upload_to='apps/convenios/anexo/arquivo'), field=models.FileField(
max_length=500, upload_to="apps/convenios/anexo/arquivo"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='anexo', model_name="anexo",
name='descricao', name="descricao",
field=models.CharField(max_length=70, verbose_name='descrição'), field=models.CharField(max_length=70, verbose_name="descrição"),
), ),
migrations.AlterField( migrations.AlterField(
model_name='anexo', model_name="anexo",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='convenio', model_name="convenio",
name='id_contrato_gescon', name="id_contrato_gescon",
field=models.CharField(blank=True, default='', editable=False, max_length=20, verbose_name='ID do contrato no Gescon'), field=models.CharField(
blank=True,
default="",
editable=False,
max_length=20,
verbose_name="ID do contrato no Gescon",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='equipamentoprevisto', model_name="equipamentoprevisto",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='gescon', model_name="gescon",
name='email', 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'), 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( migrations.AlterField(
model_name='gescon', model_name="gescon",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='projeto', model_name="projeto",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='statusconvenio', model_name="statusconvenio",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='tiposolicitacao', model_name="tiposolicitacao",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='tramitacao', model_name="tramitacao",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='tramitacao', model_name="tramitacao",
name='observacao', name="observacao",
field=models.CharField(blank=True, max_length=512, null=True, verbose_name='observação'), field=models.CharField(
blank=True, max_length=512, null=True, verbose_name="observação"
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadeadministrativa', model_name="unidadeadministrativa",
name='id', name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), field=models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadeadministrativa', model_name="unidadeadministrativa",
name='nome', name="nome",
field=models.CharField(max_length=100), field=models.CharField(max_length=100),
), ),
migrations.AlterField( migrations.AlterField(
model_name='unidadeadministrativa', model_name="unidadeadministrativa",
name='sigla', name="sigla",
field=models.CharField(max_length=10), field=models.CharField(max_length=10),
), ),
] ]

15
sigi/apps/convenios/migrations/0020_gescon_orgaos_gestores.py

@ -6,13 +6,20 @@ from django.db import migrations, models
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('convenios', '0019_alter_anexo_arquivo_alter_anexo_descricao_and_more'), (
"convenios",
"0019_alter_anexo_arquivo_alter_anexo_descricao_and_more",
),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='gescon', model_name="gescon",
name='orgaos_gestores', name="orgaos_gestores",
field=models.TextField(default='SCCO', help_text='Siglas de órgãos gestores que devem aparecer no campoORGAOSGESTORESTITULARES<ul><li>Informe um sigla por linha.</li><li>Ocorrendo qualquer uma das siglas, o contrato será importado.</li></ul>', verbose_name='Órgãos gestores'), field=models.TextField(
default="SCCO",
help_text="Siglas de órgãos gestores que devem aparecer no campoORGAOSGESTORESTITULARES<ul><li>Informe um sigla por linha.</li><li>Ocorrendo qualquer uma das siglas, o contrato será importado.</li></ul>",
verbose_name="Órgãos gestores",
),
), ),
] ]

391
sigi/apps/convenios/models.py

@ -20,99 +20,93 @@ class Projeto(models.Model):
return self.sigla return self.sigla
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
class StatusConvenio(models.Model): class StatusConvenio(models.Model):
nome = models.CharField(max_length=100) nome = models.CharField(max_length=100)
cancela = models.BooleanField(_("Cancela o convênio"), default=False) cancela = models.BooleanField(_("Cancela o convênio"), default=False)
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _("Estado de convenios") verbose_name = _("Estado de convenios")
verbose_name_plural = _("Estados de convenios") verbose_name_plural = _("Estados de convenios")
def __str__(self): def __str__(self):
return self.nome return self.nome
class TipoSolicitacao(models.Model): class TipoSolicitacao(models.Model):
nome = models.CharField(max_length=100) nome = models.CharField(max_length=100)
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
verbose_name = _("tipo de solicitação") verbose_name = _("tipo de solicitação")
verbose_name_plural = _("Tipos de solicitação") verbose_name_plural = _("Tipos de solicitação")
def __str__(self): def __str__(self):
return self.nome return self.nome
class Convenio(models.Model): class Convenio(models.Model):
casa_legislativa = models.ForeignKey( casa_legislativa = models.ForeignKey(
'casas.Orgao', "casas.Orgao",
on_delete=models.PROTECT, on_delete=models.PROTECT,
verbose_name=_('órgão conveniado') verbose_name=_("órgão conveniado"),
) )
projeto = models.ForeignKey( projeto = models.ForeignKey(
Projeto, Projeto, on_delete=models.PROTECT, verbose_name=_("Tipo de Convenio")
on_delete=models.PROTECT,
verbose_name=_('Tipo de Convenio')
) )
# numero designado pelo Senado Federal para o convênio # numero designado pelo Senado Federal para o convênio
num_processo_sf = models.CharField( num_processo_sf = models.CharField(
_('número do processo SF (Senado Federal)'), _("número do processo SF (Senado Federal)"),
max_length=20, max_length=20,
blank=True, blank=True,
help_text=_('Formatos:<br/>Antigo: <em>XXXXXX/XX-X</em>.<br/><em>SIGAD: XXXXX.XXXXXX/XXXX-XX</em>') help_text=_(
"Formatos:<br/>Antigo: <em>XXXXXX/XX-X</em>.<br/><em>SIGAD: XXXXX.XXXXXX/XXXX-XX</em>"
),
) )
# link_processo_stf = ('get_sigad_url') # link_processo_stf = ('get_sigad_url')
num_convenio = models.CharField( num_convenio = models.CharField(
_('número do convênio'), _("número do convênio"), max_length=10, blank=True
max_length=10,
blank=True
) )
id_contrato_gescon = models.CharField( id_contrato_gescon = models.CharField(
_("ID do contrato no Gescon"), _("ID do contrato no Gescon"),
max_length=20, max_length=20,
blank=True, blank=True,
default="", default="",
editable=False editable=False,
) )
data_sigi = models.DateField( data_sigi = models.DateField(
_("data de cadastro no SIGI"), _("data de cadastro no SIGI"), blank=True, null=True, auto_now_add=True
blank=True,
null=True,
auto_now_add=True
) )
data_sigad = models.DateField( data_sigad = models.DateField(
_("data de cadastro no SIGAD"), _("data de cadastro no SIGAD"), null=True, blank=True
null=True,
blank=True
) )
data_solicitacao = models.DateField( data_solicitacao = models.DateField(
_("data do e-mail de solicitação"), _("data do e-mail de solicitação"), null=True, blank=True
null=True,
blank=True
) )
tipo_solicitacao = models.ForeignKey( tipo_solicitacao = models.ForeignKey(
TipoSolicitacao, TipoSolicitacao,
on_delete=models.PROTECT, on_delete=models.PROTECT,
null=True, null=True,
blank=True, blank=True,
verbose_name=_("tipo de solicitação") verbose_name=_("tipo de solicitação"),
) )
status = models.ForeignKey( status = models.ForeignKey(
StatusConvenio, StatusConvenio,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
verbose_name=_("estado atual"), verbose_name=_("estado atual"),
null=True, null=True,
blank=True blank=True,
) )
acompanha = models.ForeignKey( acompanha = models.ForeignKey(
Servidor, Servidor,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
related_name='convenios_acompanhados', related_name="convenios_acompanhados",
verbose_name=_("acompanhado por"), verbose_name=_("acompanhado por"),
null=True, null=True,
blank=True blank=True,
) )
observacao = models.TextField( observacao = models.TextField(
_("observações"), _("observações"),
@ -124,77 +118,72 @@ class Convenio(models.Model):
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
null=True, null=True,
blank=True, blank=True,
related_name='convenios_geridos', related_name="convenios_geridos",
verbose_name=_("serviço de gestão") verbose_name=_("serviço de gestão"),
) )
servidor_gestao = models.ForeignKey( servidor_gestao = models.ForeignKey(
Servidor, Servidor,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
null=True, null=True,
blank=True, blank=True,
verbose_name=_("servidor de gestão") verbose_name=_("servidor de gestão"),
) )
data_adesao = models.DateField( data_adesao = models.DateField(
_('aderidas'), _("aderidas"),
null=True, null=True,
blank=True, blank=True,
) )
data_retorno_assinatura = models.DateField( data_retorno_assinatura = models.DateField(
_('data início vigência'), _("data início vigência"),
null=True, null=True,
blank=True, blank=True,
help_text=_('Convênio firmado.') help_text=_("Convênio firmado."),
) )
data_termino_vigencia = models.DateField( data_termino_vigencia = models.DateField(
_('Data término vigência'), _("Data término vigência"),
null=True, null=True,
blank=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_pub_diario = models.DateField(
_('data da publicação no Diário Oficial'), _("data da publicação no Diário Oficial"), null=True, blank=True
null=True,
blank=True
) )
data_termo_aceite = models.DateField( data_termo_aceite = models.DateField(
_('equipadas'), _("equipadas"),
null=True, null=True,
blank=True, blank=True,
help_text=_('Equipamentos recebidos.') help_text=_("Equipamentos recebidos."),
) )
data_devolucao_via = models.DateField( data_devolucao_via = models.DateField(
_('data de devolução da via'), _("data de devolução da via"),
null=True, null=True,
blank=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 = models.DateField(
_('data postagem correio'), _("data postagem correio"),
null=True, null=True,
blank=True, blank=True,
) )
data_devolucao_sem_assinatura = models.DateField( data_devolucao_sem_assinatura = models.DateField(
_('data de devolução por falta de assinatura'), _("data de devolução por falta de assinatura"),
null=True, null=True,
blank=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_retorno_sem_assinatura = models.DateField(
_('data do retorno sem assinatura'), _("data do retorno sem assinatura"),
null=True, null=True,
blank=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) conveniada = models.BooleanField(default=False)
equipada = models.BooleanField(default=False) equipada = models.BooleanField(default=False)
atualizacao_gescon = models.DateTimeField( atualizacao_gescon = models.DateTimeField(
_("Data de atualização pelo Gescon"), _("Data de atualização pelo Gescon"), blank=True, null=True
blank=True,
null=True
) )
observacao_gescon = models.TextField( observacao_gescon = models.TextField(
_("Observações da atualização do Gescon"), _("Observações da atualização do Gescon"), blank=True
blank=True
) )
def get_status(self): def get_status(self):
@ -207,12 +196,16 @@ class Convenio(models.Model):
return _("Vencido") return _("Vencido")
return _("Vigente") return _("Vigente")
if (self.data_retorno_assinatura is None and if (
self.data_devolucao_sem_assinatura is None and self.data_retorno_assinatura is None
self.data_retorno_sem_assinatura is None): and self.data_devolucao_sem_assinatura is None
and self.data_retorno_sem_assinatura is None
):
return _("Pendente") return _("Pendente")
if (self.data_devolucao_sem_assinatura is not None or if (
self.data_retorno_sem_assinatura is not None): self.data_devolucao_sem_assinatura is not None
or self.data_retorno_sem_assinatura is not None
):
return _("Desistência") return _("Desistência")
return _("Indefinido") return _("Indefinido")
@ -224,14 +217,14 @@ class Convenio(models.Model):
def get_sigad_url(self): def get_sigad_url(self):
m = re.match( m = re.match(
r'(?P<orgao>00100|00200)\.(?P<sequencial>\d{6})/(?P<ano>\d{4})-\d{2}', r"(?P<orgao>00100|00200)\.(?P<sequencial>\d{6})/(?P<ano>\d{4})-\d{2}",
self.num_processo_sf self.num_processo_sf,
) )
if m: if m:
orgao, sequencial, ano = m.groups() orgao, sequencial, ano = m.groups()
return ( return (
f'<a href="https://intra.senado.leg.br/sigad/novo/protocolo/' f'<a href="https://intra.senado.leg.br/sigad/novo/protocolo/'
f'impressao.asp?area=processo&txt_numero_orgao={orgao}' f"impressao.asp?area=processo&txt_numero_orgao={orgao}"
f'&txt_numero_sequencial={sequencial}&txt_numero_ano={ano}" ' f'&txt_numero_sequencial={sequencial}&txt_numero_ano={ano}" '
f'target="_blank">{self.num_processo_sf}</a>' f'target="_blank">{self.num_processo_sf}</a>'
) )
@ -243,32 +236,37 @@ class Convenio(models.Model):
super(Convenio, self).save(*args, **kwargs) super(Convenio, self).save(*args, **kwargs)
class Meta: class Meta:
get_latest_by = 'id' get_latest_by = "id"
ordering = ('id',) ordering = ("id",)
verbose_name = _('convênio') verbose_name = _("convênio")
def __str__(self): def __str__(self):
from django.conf import settings from django.conf import settings
SDF = settings.SHORT_DATE_FORMAT SDF = settings.SHORT_DATE_FORMAT
number = self.num_convenio number = self.num_convenio
project = self.projeto.sigla project = self.projeto.sigla
if ((self.data_retorno_assinatura is None) and if (self.data_retorno_assinatura is None) and (
(self.equipada and self.data_termo_aceite is not None)): self.equipada and self.data_termo_aceite is not None
):
date = date_format(self.data_termo_aceite, SDF) date = date_format(self.data_termo_aceite, SDF)
return _(f"{project}{number} - equipada em {date}") return _(f"{project}{number} - equipada em {date}")
elif self.data_retorno_assinatura is None: elif self.data_retorno_assinatura is None:
date = (date_format(self.data_adesao, SDF) date = (
if self.data_adesao else "") date_format(self.data_adesao, SDF) if self.data_adesao else ""
)
return _(f"{project}, nº {number}, início em {date}") return _(f"{project}, nº {number}, início em {date}")
if ((self.data_retorno_assinatura is not None) and not if (self.data_retorno_assinatura is not None) and not (
(self.equipada and self.data_termo_aceite is not None)): self.equipada and self.data_termo_aceite is not None
):
date = date_format(self.data_retorno_assinatura, SDF) date = date_format(self.data_retorno_assinatura, SDF)
status = self.get_status() status = self.get_status()
return _( return _(
f"{project}, nº {number}, inicio em {date}. Status: {status}" f"{project}, nº {number}, inicio em {date}. Status: {status}"
) )
if ((self.data_retorno_assinatura is not None) and if (self.data_retorno_assinatura is not None) and (
(self.equipada and self.data_termo_aceite is not None)): self.equipada and self.data_termo_aceite is not None
):
date = date_format(self.data_retorno_assinatura, SDF) 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 _( return _(
@ -276,45 +274,44 @@ class Convenio(models.Model):
f"{equipped_date}. Status: {self.get_status()}" f"{equipped_date}. Status: {self.get_status()}"
) )
class EquipamentoPrevisto(models.Model): class EquipamentoPrevisto(models.Model):
convenio = models.ForeignKey( convenio = models.ForeignKey(
Convenio, Convenio, on_delete=models.CASCADE, verbose_name=_("convênio")
on_delete=models.CASCADE,
verbose_name=_('convênio')
) )
equipamento = models.ForeignKey( equipamento = models.ForeignKey(
'inventario.Equipamento', "inventario.Equipamento", on_delete=models.CASCADE
on_delete=models.CASCADE
) )
quantidade = models.PositiveSmallIntegerField(default=1) quantidade = models.PositiveSmallIntegerField(default=1)
class Meta: class Meta:
verbose_name = _('equipamento previsto') verbose_name = _("equipamento previsto")
verbose_name_plural = _('equipamentos previstos') verbose_name_plural = _("equipamentos previstos")
def __str__(self): def __str__(self):
return _(f"{self.quantidade} {self.equipamento}(s)") return _(f"{self.quantidade} {self.equipamento}(s)")
class Anexo(models.Model): class Anexo(models.Model):
convenio = models.ForeignKey( convenio = models.ForeignKey(
Convenio, Convenio, on_delete=models.CASCADE, verbose_name=_("convênio")
on_delete=models.CASCADE,
verbose_name=_('convênio')
) )
# caminho no sistema para o documento anexo # caminho no sistema para o documento anexo
arquivo = models.FileField(upload_to='apps/convenios/anexo/arquivo', max_length=500) arquivo = models.FileField(
descricao = models.CharField(_('descrição'), max_length=70) upload_to="apps/convenios/anexo/arquivo", max_length=500
)
descricao = models.CharField(_("descrição"), max_length=70)
data_pub = models.DateTimeField( data_pub = models.DateTimeField(
_('data da publicação do anexo'), _("data da publicação do anexo"), default=datetime.now
default=datetime.now
) )
class Meta: class Meta:
ordering = ('-data_pub',) ordering = ("-data_pub",)
def __str__(self): def __str__(self):
return _(f"{self.descricao} publicado em {self.data_pub}") return _(f"{self.descricao} publicado em {self.data_pub}")
class UnidadeAdministrativa(models.Model): class UnidadeAdministrativa(models.Model):
sigla = models.CharField(max_length=10) sigla = models.CharField(max_length=10)
nome = models.CharField(max_length=100) nome = models.CharField(max_length=100)
@ -322,27 +319,26 @@ class UnidadeAdministrativa(models.Model):
def __str__(self): def __str__(self):
return self.sigla return self.sigla
class Tramitacao(models.Model): class Tramitacao(models.Model):
convenio = models.ForeignKey( convenio = models.ForeignKey(
Convenio, Convenio, on_delete=models.CASCADE, verbose_name=_("convênio")
on_delete=models.CASCADE,
verbose_name=_('convênio')
) )
unid_admin = models.ForeignKey( unid_admin = models.ForeignKey(
UnidadeAdministrativa, UnidadeAdministrativa,
on_delete=models.PROTECT, on_delete=models.PROTECT,
verbose_name=_('Unidade Administrativa') verbose_name=_("Unidade Administrativa"),
) )
data = models.DateField() data = models.DateField()
observacao = models.CharField( observacao = models.CharField(
_('observação'), _("observação"),
max_length=512, max_length=512,
null=True, null=True,
blank=True, blank=True,
) )
class Meta: class Meta:
verbose_name_plural = _('Tramitações') verbose_name_plural = _("Tramitações")
def __str__(self): def __str__(self):
in_date = _(f"em {self.data}") # for focused translation in_date = _(f"em {self.data}") # for focused translation
@ -351,53 +347,65 @@ class Tramitacao(models.Model):
result = f"{result} ({self.observacao})" result = f"{result} ({self.observacao})"
return result return result
class Gescon(models.Model): class Gescon(models.Model):
url_gescon = models.URLField( url_gescon = models.URLField(
_("Webservice Gescon"), _("Webservice Gescon"),
default=("https://adm.senado.gov.br/gestao-contratos/api/contratos" default=(
"/busca?especie={s}"), "https://adm.senado.gov.br/gestao-contratos/api/contratos"
help_text=_("Informe o ponto de consulta do webservice do Gescon, " "/busca?especie={s}"
),
help_text=_(
"Informe o ponto de consulta do webservice do Gescon, "
"inclusive com a querystring. No ponto onde deve ser " "inclusive com a querystring. No ponto onde deve ser "
"inserida a sigla da subespecie do contrato, use a " "inserida a sigla da subespecie do contrato, use a "
"marcação {s}.<br/><strong>Por exemplo:</strong> " "marcação {s}.<br/><strong>Por exemplo:</strong> "
"https://adm.senado.gov.br/gestao-contratos/api/contratos" "https://adm.senado.gov.br/gestao-contratos/api/contratos"
"/busca?especie=<strong>{s}</strong>") "/busca?especie=<strong>{s}</strong>"
),
) )
subespecies = models.TextField( subespecies = models.TextField(
_("Subespécies"), _("Subespécies"),
default="AC=ACT\nPI=PI\nCN=PML\nTA=PML", default="AC=ACT\nPI=PI\nCN=PML\nTA=PML",
help_text=_("Informe as siglas das subespécies de contratos que " help_text=_(
"Informe as siglas das subespécies de contratos que "
"devem ser pesquisados no Gescon com a sigla " "devem ser pesquisados no Gescon com a sigla "
"correspondente do projeto no SIGI. Coloque um par de " "correspondente do projeto no SIGI. Coloque um par de "
"siglas por linha, no formato SIGLA_GESTON=SIGLA_SIGI. " "siglas por linha, no formato SIGLA_GESTON=SIGLA_SIGI. "
"As siglas não encontradas serão ignoradas.") "As siglas não encontradas serão ignoradas."
),
) )
palavras = models.TextField( palavras = models.TextField(
_("Palavras de filtro"), _("Palavras de filtro"),
default="ILB\nINTERLEGIS", default="ILB\nINTERLEGIS",
help_text=_("Palavras que devem aparecer no campo OBJETO dos dados do " help_text=_(
"Palavras que devem aparecer no campo OBJETO dos dados do "
"Gescon para identificar se o contrato pertence ao ILB. " "Gescon para identificar se o contrato pertence ao ILB. "
"<ul><li>Informe uma palavra por linha.</li>" "<ul><li>Informe uma palavra por linha.</li>"
"<li>Ocorrendo qualquer uma das palavras, o contrato será " "<li>Ocorrendo qualquer uma das palavras, o contrato será "
"importado.</li></ul>") "importado.</li></ul>"
),
) )
orgaos_gestores = models.TextField( orgaos_gestores = models.TextField(
_("Órgãos gestores"), _("Órgãos gestores"),
default="SCCO", default="SCCO",
help_text=_("Siglas de órgãos gestores que devem aparecer no campo" help_text=_(
"Siglas de órgãos gestores que devem aparecer no campo"
"ORGAOSGESTORESTITULARES" "ORGAOSGESTORESTITULARES"
"<ul><li>Informe um sigla por linha.</li>" "<ul><li>Informe um sigla por linha.</li>"
"<li>Ocorrendo qualquer uma das siglas, o contrato será " "<li>Ocorrendo qualquer uma das siglas, o contrato será "
"importado.</li></ul>") "importado.</li></ul>"
),
) )
email = models.EmailField( email = models.EmailField(
_("E-mail"), _("E-mail"),
help_text=_("Caixa de e-mail para onde o relatório diário de " help_text=_(
"importação será enviado.") "Caixa de e-mail para onde o relatório diário de "
"importação será enviado."
),
) )
ultima_importacao = models.TextField( ultima_importacao = models.TextField(
_("Resultado da última importação"), _("Resultado da última importação"), blank=True
blank=True
) )
class Meta: class Meta:
@ -426,7 +434,7 @@ class Gescon(models.Model):
subject=_("Relatório de importação GESCON"), subject=_("Relatório de importação GESCON"),
message=self.ultima_importacao, message=self.ultima_importacao,
recipient_list=self.email, recipient_list=self.email,
fail_silently=True fail_silently=True,
) )
else: else:
self.ultima_importacao += _( self.ultima_importacao += _(
@ -438,17 +446,25 @@ class Gescon(models.Model):
def importa_contratos(self): def importa_contratos(self):
self.ultima_importacao = "" self.ultima_importacao = ""
self.add_message( 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 == "": if self.palavras == "" or self.orgaos_gestores == "":
self.add_message(_("Nenhuma palavra de pesquisa ou orgãos " self.add_message(
"gestores definidos - processo abortado."), True) _(
"Nenhuma palavra de pesquisa ou orgãos "
"gestores definidos - processo abortado."
),
True,
)
if self.subespecies == "": if self.subespecies == "":
self.add_message(_("Nenhuma subespécie definida - processo " self.add_message(
"abortado."), True) _("Nenhuma subespécie definida - processo " "abortado."), True
)
return return
if "{s}" not in self.url_gescon: 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 " "inserir a sigla da subespécia na consulta ao webservice "
"- processo abortado." "- processo abortado."
), ),
True True,
) )
return return
palavras = self.palavras.split() palavras = self.palavras.split()
orgaos = self.orgaos_gestores.split() orgaos = self.orgaos_gestores.split()
subespecies = {tuple(s.split("=")) for s in self.subespecies.split()} subespecies = {tuple(s.split("=")) for s in self.subespecies.split()}
lista_cnpj = {re.sub("[^\d]", "", o.cnpj).zfill(14): o lista_cnpj = {
re.sub("[^\d]", "", o.cnpj).zfill(14): o
for o in Orgao.objects.exclude(cnpj="") for o in Orgao.objects.exclude(cnpj="")
if re.sub("[^\d]", "", o.cnpj) != ''} if re.sub("[^\d]", "", o.cnpj) != ""
}
for sigla_gescon, sigla_sigi in subespecies: for sigla_gescon, sigla_sigi in subespecies:
self.add_message(_(f"\nImportando subespécie {sigla_gescon}")) self.add_message(_(f"\nImportando subespécie {sigla_gescon}"))
@ -487,9 +505,13 @@ class Gescon(models.Model):
) )
continue continue
if not 'application/json' in response.headers.get('Content-Type'): if not "application/json" in response.headers.get("Content-Type"):
self.add_message(_(f"\tResultado da consulta à {url} não " self.add_message(
"retornou dados em formato json")) _(
f"\tResultado da consulta à {url} não "
"retornou dados em formato json"
)
)
continue continue
contratos = response.json() contratos = response.json()
@ -497,11 +519,14 @@ class Gescon(models.Model):
# Pegar só os contratos que possuem alguma das palavras-chave # Pegar só os contratos que possuem alguma das palavras-chave
nossos = [ nossos = [
c for c in contratos c
if any(palavra in c['objeto'] for palavra in palavras) or for c in contratos
any(orgao in c['orgaosGestoresTitulares'] if any(palavra in c["objeto"] for palavra in palavras)
or any(
orgao in c["orgaosGestoresTitulares"]
for orgao in orgaos for orgao in orgaos
if c['orgaosGestoresTitulares'] is not None) if c["orgaosGestoresTitulares"] is not None
)
] ]
self.add_message( self.add_message(
@ -514,23 +539,25 @@ class Gescon(models.Model):
atualizados = 0 atualizados = 0
for contrato in nossos: for contrato in nossos:
numero = contrato['numero'].zfill(8) numero = contrato["numero"].zfill(8)
numero = f"{numero[:4]}/{numero[4:]}" 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:]}" sigad = f"{sigad[:5]}.{sigad[5:11]}/{sigad[11:15]}-{sigad[15:]}"
if contrato['cnpjCpfFornecedor']: if contrato["cnpjCpfFornecedor"]:
cnpj = contrato['cnpjCpfFornecedor'].zfill(14) cnpj = contrato["cnpjCpfFornecedor"].zfill(14)
cnpj_masked = (f"{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/" cnpj_masked = (
f"{cnpj[8:12]}-{cnpj[12:]}") f"{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/"
f"{cnpj[8:12]}-{cnpj[12:]}"
)
else: else:
cnpj = None cnpj = None
if contrato['nomeFornecedor']: if contrato["nomeFornecedor"]:
nome = contrato['nomeFornecedor'] nome = contrato["nomeFornecedor"]
nome = nome.replace('VEREADORES DE', '') nome = nome.replace("VEREADORES DE", "")
nome = nome.split('-')[0] nome = nome.split("-")[0]
nome = nome.split('/')[0] nome = nome.split("/")[0]
nome = nome.strip() nome = nome.strip()
nome = nome.replace(" ", " ") nome = nome.replace(" ", " ")
nome = to_ascii(nome) nome = to_ascii(nome)
@ -539,8 +566,10 @@ class Gescon(models.Model):
if (cnpj is None) and (nome is None): if (cnpj is None) and (nome is None):
self.add_message( 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 erros += 1
continue continue
@ -555,7 +584,8 @@ class Gescon(models.Model):
orgao = Orgao.objects.get(cnpj=cnpj_masked) orgao = Orgao.objects.get(cnpj=cnpj_masked)
except ( except (
Orgao.DoesNotExist, Orgao.DoesNotExist,
Orgao.MultipleObjectsReturned) as e: Orgao.MultipleObjectsReturned,
) as e:
orgao = None orgao = None
pass pass
@ -564,17 +594,20 @@ class Gescon(models.Model):
orgao = Orgao.objects.get(search_text__iexact=nome) orgao = Orgao.objects.get(search_text__iexact=nome)
except ( except (
Orgao.DoesNotExist, Orgao.DoesNotExist,
Orgao.MultipleObjectsReturned) as e: Orgao.MultipleObjectsReturned,
) as e:
orgao = None orgao = None
pass pass
if orgao is None: if orgao is None:
self.add_message( self.add_message(
_(f"\tÓrgão não encontrado no SIGI ou mais de um órgão" _(
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"encontrado com o mesmo CNPJ ou nome. Favor "
f"regularizar o cadastro: " f"regularizar o cadastro: "
f"CNPJ: {contrato['cnpjCpfFornecedor']}, " f"CNPJ: {contrato['cnpjCpfFornecedor']}, "
f"Nome: {contrato['nomeFornecedor']}") f"Nome: {contrato['nomeFornecedor']}"
)
) )
erros += 1 erros += 1
continue continue
@ -587,8 +620,7 @@ class Gescon(models.Model):
# NUP não encontrado, talvez exista apenas com o número # NUP não encontrado, talvez exista apenas com o número
# do GESCON # do GESCON
convenios = Convenio.objects.filter( convenios = Convenio.objects.filter(
Q(num_convenio=numero) | Q(num_convenio=numero) | Q(num_processo_sf=numero)
Q(num_processo_sf=numero)
) )
chk = convenios.count() chk = convenios.count()
if chk > 1: if chk > 1:
@ -608,14 +640,15 @@ class Gescon(models.Model):
num_processo_sf=sigad, num_processo_sf=sigad,
num_convenio=numero, num_convenio=numero,
data_sigi=date.today(), data_sigi=date.today(),
data_sigad=contrato['assinatura'], data_sigad=contrato["assinatura"],
observacao=contrato['objeto'], observacao=contrato["objeto"],
data_retorno_assinatura=contrato['inicioVigencia'], data_retorno_assinatura=contrato["inicioVigencia"],
data_termino_vigencia=contrato['terminoVigencia'], data_termino_vigencia=contrato["terminoVigencia"],
data_pub_diario=contrato['publicacao'], data_pub_diario=contrato["publicacao"],
atualizacao_gescon=datetime.now(), atualizacao_gescon=datetime.now(),
observacao_gescon=_("Importado integralmente do" observacao_gescon=_(
"Gescon") "Importado integralmente do" "Gescon"
),
) )
convenio.save() convenio.save()
novos += 1 novos += 1
@ -623,15 +656,17 @@ class Gescon(models.Model):
elif chk == 1: elif chk == 1:
convenio = convenios.get() convenio = convenios.get()
convenio.atualizacao_gescon = datetime.now() convenio.atualizacao_gescon = datetime.now()
convenio.observacao_gescon = '' convenio.observacao_gescon = ""
if convenio.casa_legislativa != orgao: if convenio.casa_legislativa != orgao:
self.add_message( self.add_message(
_(f"\tO órgao no convênio {convenio.id} diverge do " _(
f"\tO órgao no convênio {convenio.id} diverge do "
f"que consta no Gescon ({cnpj}, " f"que consta no Gescon ({cnpj}, "
f"{contrato['nomeFornecedor']})") f"{contrato['nomeFornecedor']})"
)
) )
convenio.observacao_gescon = _( convenio.observacao_gescon = _(
'ERRO: Órgão diverge do Gescon. Não atualizado!' "ERRO: Órgão diverge do Gescon. Não atualizado!"
) )
convenio.save() convenio.save()
erros += 1 erros += 1
@ -639,11 +674,13 @@ class Gescon(models.Model):
if convenio.num_processo_sf != sigad: if convenio.num_processo_sf != sigad:
self.add_message( self.add_message(
_(f"\tO contrato Gescon nº {numero} corresponde" _(
f"\tO contrato Gescon nº {numero} corresponde"
f" ao convênio SIGI {convenio.id}, mas o NUP " f" ao convênio SIGI {convenio.id}, mas o NUP "
f"sigad diverge (Gescon: {sigad}, " f"sigad diverge (Gescon: {sigad}, "
f"SIGI: {convenio.num_processo_sf}). " f"SIGI: {convenio.num_processo_sf}). "
"CORRIGIDO!") "CORRIGIDO!"
)
) )
convenio.num_processo_sf = sigad convenio.num_processo_sf = sigad
convenio.observacao_gescon += _( convenio.observacao_gescon += _(
@ -653,11 +690,13 @@ class Gescon(models.Model):
if convenio.num_convenio != numero: if convenio.num_convenio != numero:
self.add_message( self.add_message(
_(f"\tO contrato Gescon ID {contrato['id']} " _(
f"\tO contrato Gescon ID {contrato['id']} "
f"corresponde ao convênio SIGI {convenio.id}, " f"corresponde ao convênio SIGI {convenio.id}, "
"mas o número do convênio diverge (" "mas o número do convênio diverge ("
f"Gescon: {numero}, SIGI: {convenio.num_convenio}" f"Gescon: {numero}, SIGI: {convenio.num_convenio}"
"). CORRIGIDO!") "). CORRIGIDO!"
)
) )
convenio.num_convenio = numero convenio.num_convenio = numero
convenio.observacao_gescon += _( convenio.observacao_gescon += _(
@ -665,23 +704,21 @@ class Gescon(models.Model):
) )
alertas += 1 alertas += 1
if contrato['objeto'] not in convenio.observacao: if contrato["objeto"] not in convenio.observacao:
convenio.observacao += "\n" + contrato['objeto'] convenio.observacao += "\n" + contrato["objeto"]
convenio.observacao_gescon += _( convenio.observacao_gescon += _(
"Observação atualizada.\n" "Observação atualizada.\n"
) )
convenio.data_sigad = contrato['assinatura'] convenio.data_sigad = contrato["assinatura"]
convenio.data_retorno_assinatura = contrato[ convenio.data_retorno_assinatura = contrato[
'inicioVigencia' "inicioVigencia"
] ]
convenio.data_termino_vigencia = contrato[ convenio.data_termino_vigencia = contrato["terminoVigencia"]
'terminoVigencia' convenio.data_pub_diario = contrato["publicacao"]
] if contrato["codTextoContrato"]:
convenio.data_pub_diario = contrato['publicacao']
if contrato['codTextoContrato']:
convenio.id_contrato_gescon = contrato[ convenio.id_contrato_gescon = contrato[
'codTextoContrato' "codTextoContrato"
] ]
else: else:
convenio.id_contrato_gescon = "" convenio.id_contrato_gescon = ""
@ -690,10 +727,12 @@ class Gescon(models.Model):
convenio.save() convenio.save()
except Exception as e: except Exception as e:
self.add_message( self.add_message(
_("Ocorreu um erro ao salvar o convênio " _(
"Ocorreu um erro ao salvar o convênio "
f"{convenio.id} no SIGI. Alguma informação do " f"{convenio.id} no SIGI. Alguma informação do "
"Gescon pode ter quebrado o sistema. Informe ao " "Gescon pode ter quebrado o sistema. Informe ao "
f"suporte. Erro: {e.message}") f"suporte. Erro: {e.message}"
)
) )
erros += 1 erros += 1
continue continue
@ -701,17 +740,21 @@ class Gescon(models.Model):
atualizados += 1 atualizados += 1
else: else:
self.add_message( self.add_message(
_(f"\tExistem {chk} convênios no SIGI que " _(
f"\tExistem {chk} convênios no SIGI que "
"correspondem ao mesmo contrato no Gescon (contrato " "correspondem ao mesmo contrato no Gescon (contrato "
f"{numero}, sigad {sigad})") f"{numero}, sigad {sigad})"
)
) )
erros += 1 erros += 1
continue continue
self.add_message( self.add_message(
_(f"\t{novos} novos convenios adicionados ao SIGI, " _(
f"\t{novos} novos convenios adicionados ao SIGI, "
f"{atualizados} atualizados, sendo {alertas} com alertas, e " f"{atualizados} atualizados, sendo {alertas} com alertas, e "
f"{erros} reportados com erro.") f"{erros} reportados com erro."
)
) )
self.save() self.save()

165
sigi/apps/convenios/reports.py

@ -1,5 +1,11 @@
from django.utils.translation import gettext as _ 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 reportlab.lib.units import cm
from sigi.apps.relatorios.reports import ReportDefault from sigi.apps.relatorios.reports import ReportDefault
@ -25,7 +31,7 @@ class SemEquipamentosReport(object):
class ConvenioReport(ReportDefault): class ConvenioReport(ReportDefault):
title = _('Relatório de Parcerias') title = _("Relatório de Parcerias")
class band_page_header(ReportDefault.band_page_header): class band_page_header(ReportDefault.band_page_header):
@ -86,36 +92,37 @@ class ConvenioReport(ReportDefault):
elements = [ elements = [
ObjectValue( ObjectValue(
attribute_name='casa_legislativa.municipio.uf.sigla', attribute_name="casa_legislativa.municipio.uf.sigla",
left=label_left[0] * cm left=label_left[0] * cm,
),
ObjectValue(
attribute_name='casa_legislativa.municipio.nome',
left=label_left[1] * cm
), ),
ObjectValue( ObjectValue(
attribute_name='num_convenio', attribute_name="casa_legislativa.municipio.nome",
left=label_left[2] * cm left=label_left[1] * cm,
), ),
ObjectValue(attribute_name="num_convenio", left=label_left[2] * cm),
ObjectValue( ObjectValue(
attribute_name='projeto.sigla', attribute_name="projeto.sigla", left=label_left[3] * cm
left=label_left[3] * cm
), ),
ObjectValue( ObjectValue(
attribute_name='data_retorno_assinatura', attribute_name="data_retorno_assinatura",
left=label_left[4] * cm, left=label_left[4] * cm,
get_value=lambda instance: get_value=lambda instance: instance.data_retorno_assinatura.strftime(
instance.data_retorno_assinatura.strftime('%d/%m/%Y') if instance.data_retorno_assinatura is not None else '-' "%d/%m/%Y"
)
if instance.data_retorno_assinatura is not None
else "-",
), ),
ObjectValue( ObjectValue(
attribute_name='data_pub_diario', attribute_name="data_pub_diario",
left=label_left[5] * cm, left=label_left[5] * cm,
get_value=lambda instance: get_value=lambda instance: instance.data_pub_diario.strftime(
instance.data_pub_diario.strftime('%d/%m/%Y') if instance.data_pub_diario is not None else '-' "%d/%m/%Y"
)
if instance.data_pub_diario is not None
else "-",
), ),
ObjectValue( ObjectValue(
attribute_name='casa_legislativa.nome', attribute_name="casa_legislativa.nome", left=label_left[6] * cm
left=label_left[6] * cm
), ),
] ]
@ -135,7 +142,6 @@ class ConvenioReport(ReportDefault):
class ConvenioReportSemAceite(ConvenioReport): class ConvenioReportSemAceite(ConvenioReport):
class band_page_header(ReportDefault.band_page_header): class band_page_header(ReportDefault.band_page_header):
label_top = ReportDefault.band_page_header.label_top label_top = ReportDefault.band_page_header.label_top
@ -186,39 +192,38 @@ class ConvenioReportSemAceite(ConvenioReport):
elements = [ elements = [
ObjectValue( ObjectValue(
attribute_name='casa_legislativa.municipio.uf.sigla', attribute_name="casa_legislativa.municipio.uf.sigla",
left=label_left[0] * cm left=label_left[0] * cm,
),
ObjectValue(
attribute_name='casa_legislativa.municipio.nome',
left=label_left[1] * cm
), ),
ObjectValue( ObjectValue(
attribute_name='num_convenio', attribute_name="casa_legislativa.municipio.nome",
left=label_left[2] * cm left=label_left[1] * cm,
), ),
ObjectValue(attribute_name="num_convenio", left=label_left[2] * cm),
ObjectValue( ObjectValue(
attribute_name='projeto.sigla', attribute_name="projeto.sigla",
left=label_left[3], left=label_left[3],
), ),
ObjectValue( ObjectValue(
attribute_name='data_retorno_assinatura', attribute_name="data_retorno_assinatura",
left=label_left[4] * cm, left=label_left[4] * cm,
get_value=lambda instance: get_value=lambda instance: instance.data_retorno_assinatura.strftime(
instance.data_retorno_assinatura.strftime('%d/%m/%Y') if instance.data_retorno_assinatura is not None else '-' "%d/%m/%Y"
)
if instance.data_retorno_assinatura is not None
else "-",
), ),
ObjectValue( ObjectValue(
attribute_name='casa_legislativa.nome', attribute_name="casa_legislativa.nome", left=label_left[5] * cm
left=label_left[5] * cm
), ),
] ]
float_duas_casas = lambda instance: '%.2f' % (instance) float_duas_casas = lambda instance: "%.2f" % (instance)
class ConvenioReportRegiao(ReportDefault): 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): class band_page_header(ReportDefault.band_page_header):
label_top = ReportDefault.band_page_header.label_top label_top = ReportDefault.band_page_header.label_top
@ -228,57 +233,103 @@ class ConvenioReportRegiao(ReportDefault):
elements = list(ReportDefault.band_page_header.elements) elements = list(ReportDefault.band_page_header.elements)
elements += [ elements += [
Label(text=_("UF"), left=label_left[0] * cm, top=label_top,), Label(
Label(text=_("Total"), left=label_left[1] * cm, top=label_top,), text=_("UF"),
Label(text=_("Aderidas"), left=label_left[2] * cm, top=label_top,), 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="%", 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), Label(text="%", left=label_left[5] * cm, top=label_top),
] ]
class band_detail(ReportDefault.band_detail): class band_detail(ReportDefault.band_detail):
label_left = [0.5, 6, 8, 10, 12, 14] label_left = [0.5, 6, 8, 10, 12, 14]
display_inline = True display_inline = True
float_duas_casas = lambda instance: '%.2f' % (instance.porc_casas_aderidas) float_duas_casas = lambda instance: "%.2f" % (
default_style = {'fontName': 'Helvetica', 'fontSize': 11} instance.porc_casas_aderidas
)
default_style = {"fontName": "Helvetica", "fontSize": 11}
elements = [ elements = [
ObjectValue(attribute_name='estado', left=label_left[0] * cm, ), ObjectValue(
ObjectValue(attribute_name='quant_casas', left=label_left[1] * cm,), attribute_name="estado",
ObjectValue(attribute_name='quant_casas_aderidas', left=label_left[2] * cm), left=label_left[0] * 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(
ObjectValue(attribute_name='porc_casas_nao_aderidas', left=label_left[5] * cm,), 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): class band_summary(ReportBand):
label_left = [0.5, 6, 8, 10, 12, 14] label_left = [0.5, 6, 8, 10, 12, 14]
elements = [ elements = [
Label(text=_("Total"), top=0.1 * cm, left=label_left[0] * cm), 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(
ObjectValue(attribute_name='quant_casas_aderidas', action=FIELD_ACTION_SUM, left=label_left[2] * cm), 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, # 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), # 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, # ObjectValue(attribute_name='porc_casas_nao_aderidas', left=label_left[5]*cm,
# get_value=lambda x: teste(), # get_value=lambda x: teste(),
# ), # ),
] ]
borders = {'top': True} borders = {"top": True}
class ConvenioPorCMReport(ConvenioReport): class ConvenioPorCMReport(ConvenioReport):
title = _('Relatório de Parcerias por Câmara Municipal') title = _("Relatório de Parcerias por Câmara Municipal")
class ConvenioPorALReport(ConvenioReport): class ConvenioPorALReport(ConvenioReport):
title = _('Relatório de Parcerias por Assembléia Legislativa') title = _("Relatório de Parcerias por Assembléia Legislativa")
class ConvenioReportSemAceiteCM(ConvenioReportSemAceite): class ConvenioReportSemAceiteCM(ConvenioReportSemAceite):
title = _('Relatório de Parcerias por Câmara Municipal') title = _("Relatório de Parcerias por Câmara Municipal")
class ConvenioReportSemAceiteAL(ConvenioReportSemAceite): class ConvenioReportSemAceiteAL(ConvenioReportSemAceite):
title = _('Relatório de Parcerias por Assembléia Legislativa') title = _("Relatório de Parcerias por Assembléia Legislativa")

8
sigi/apps/convenios/urls.py

@ -2,8 +2,12 @@ from django.urls import path
from sigi.apps.convenios import views from sigi.apps.convenios import views
urlpatterns = [ urlpatterns = [
path('reportsRegiao/<str:regiao>/', views.report_regiao, name='convenios-report_regiao_pdf'), path(
path('importar/', views.importar_gescon, name='importar-gescon'), "reportsRegiao/<str:regiao>/",
views.report_regiao,
name="convenios-report_regiao_pdf",
),
path("importar/", views.importar_gescon, name="importar-gescon"),
] ]
# urlpatterns = patterns( # urlpatterns = patterns(

68
sigi/apps/convenios/views.py

@ -1,9 +1,11 @@
import csv import csv
import datetime import datetime
# from django.contrib import messages # from django.contrib import messages
from django.contrib import admin from django.contrib import admin
from django.http.response import HttpResponseForbidden from django.http.response import HttpResponseForbidden
# from django.conf import settings # from django.conf import settings
# from django.core.paginator import Paginator, InvalidPage, EmptyPage # from django.core.paginator import Paginator, InvalidPage, EmptyPage
# from django.http import HttpResponse, HttpResponseRedirect # 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.casas.models import Orgao
from sigi.apps.contatos.models import UnidadeFederativa from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.convenios.models import Convenio, Gescon, Projeto from sigi.apps.convenios.models import Convenio, Gescon, Projeto
# from sigi.apps.convenios.reports import (ConvenioReport, # from sigi.apps.convenios.reports import (ConvenioReport,
# ConvenioReportSemAceite, # ConvenioReportSemAceite,
# ConvenioPorCMReport, # ConvenioPorCMReport,
@ -22,14 +25,15 @@ from sigi.apps.convenios.models import Convenio, Gescon, Projeto
# ConvenioReportSemAceiteAL, # ConvenioReportSemAceiteAL,
# ConvenioReportSemAceiteCM) # ConvenioReportSemAceiteCM)
@login_required @login_required
def report_regiao(request, regiao): def report_regiao(request, regiao):
REGIAO_CHOICES = dict(UnidadeFederativa.REGIAO_CHOICES) REGIAO_CHOICES = dict(UnidadeFederativa.REGIAO_CHOICES)
projetos = Projeto.objects.all() projetos = Projeto.objects.all()
camaras = Orgao.objects.filter(tipo__sigla='CM') camaras = Orgao.objects.filter(tipo__sigla="CM")
tabelas = list() 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 = casas_estado_to_tabela(camaras, convenios, regiao)
tabela["projeto"] = _("Geral") tabela["projeto"] = _("Geral")
@ -42,22 +46,23 @@ def report_regiao(request, regiao):
tabelas.append(tabela) tabelas.append(tabela)
context = { context = {
'tabelas': tabelas, "tabelas": tabelas,
'regiao': REGIAO_CHOICES[regiao], "regiao": REGIAO_CHOICES[regiao],
} }
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename=f'relatorio_regiao_{ regiao }.pdf', filename=f"relatorio_regiao_{ regiao }.pdf",
request=request, request=request,
template='convenios/tabela_regiao.html', template="convenios/tabela_regiao.html",
context=context, context=context,
content_type='application/pdf', content_type="application/pdf",
) )
def casas_estado_to_tabela(casas, convenios, regiao): def casas_estado_to_tabela(casas, convenios, regiao):
estados = get_list_or_404(UnidadeFederativa, regiao=regiao) estados = get_list_or_404(UnidadeFederativa, regiao=regiao)
class LinhaEstado(): class LinhaEstado:
pass pass
lista = [] lista = []
@ -107,21 +112,21 @@ def casas_estado_to_tabela(casas, convenios, regiao):
casas_regiao.count(), casas_regiao.count(),
casas_regiao.exclude(convenio__in=convenios_regiao).distinct().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).distinct().count(),
casas_regiao.filter( casas_regiao.filter(convenio__in=convenios_regiao_publicados)
convenio__in=convenios_regiao_publicados .distinct()
).distinct().count(), .count(),
casas_regiao.filter( casas_regiao.filter(convenio__in=convenios_regiao_equipados)
convenio__in=convenios_regiao_equipados .distinct()
).distinct().count(), .count(),
) )
cabecalho_topo = ( cabecalho_topo = (
_('UF'), _("UF"),
_('Câmaras municipais'), _("Câmaras municipais"),
_('Não Aderidas'), _("Não Aderidas"),
_('Aderidas'), _("Aderidas"),
_('Conveniadas'), _("Conveniadas"),
_('Equipadas') _("Equipadas"),
) )
return { return {
@ -130,6 +135,7 @@ def casas_estado_to_tabela(casas, convenios, regiao):
"sumario": sumario, "sumario": sumario,
} }
@login_required @login_required
def importar_gescon(request): def importar_gescon(request):
if not request.user.is_superuser: if not request.user.is_superuser:
@ -137,18 +143,17 @@ def importar_gescon(request):
context = admin.site.each_context(request) context = admin.site.each_context(request)
action = request.GET.get('action', "") action = request.GET.get("action", "")
gescon = Gescon.load() gescon = Gescon.load()
if action == 'importar': if action == "importar":
gescon.importa_contratos() gescon.importa_contratos()
context['gescon'] = gescon context["gescon"] = gescon
return render(request, "convenios/importar_gescon.html", context) return render(request, "convenios/importar_gescon.html", context)
""" """
def query_ordena(qs, o, ot): def query_ordena(qs, o, ot):
list_display = ('num_convenio', 'casa_legislativa', list_display = ('num_convenio', 'casa_legislativa',
@ -163,18 +168,23 @@ def query_ordena(qs, o, ot):
qs = qs.order_by("-" + aux) qs = qs.order_by("-" + aux)
return qs return qs
""" """
def normaliza_data(get, nome_param): def normaliza_data(get, nome_param):
import re import re
if nome_param in get: if nome_param in get:
value = get.get(nome_param, '') value = get.get(nome_param, "")
if value == '': if value == "":
del get[nome_param] del get[nome_param]
elif re.match('^\d*$', value): # Year only elif re.match("^\d*$", value): # Year only
# Complete with january 1st # Complete with january 1st
get[nome_param] = "%s-01-01" % value 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 # Complete with 1st day of month
get[nome_param] = '%s-01' % value get[nome_param] = "%s-01" % value
""" """
def get_for_qs(get, qs): def get_for_qs(get, qs):
kwargs = {} kwargs = {}

188
sigi/apps/diagnosticos/admin.py

@ -6,7 +6,14 @@ from django.utils.translation import gettext as _
from eav.admin import BaseEntityAdmin, BaseSchemaAdmin from eav.admin import BaseEntityAdmin, BaseSchemaAdmin
from sigi.apps.diagnosticos.forms import DiagnosticoForm 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 from sigi.apps.utils.base_admin import BaseModelAdmin
@ -22,14 +29,22 @@ def publicar_diagnostico(self, request, queryset):
if email: if email:
diagnostico.email_diagnostico_publicado(email, request.get_host()) diagnostico.email_diagnostico_publicado(email, request.get_host())
self.message_user(request, _("Diagnóstico(s) publicado(s) com sucesso!")) 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): def despublicar_diagnostico(self, request, queryset):
queryset.update(publicado=False) 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): class EquipeInline(admin.TabularInline):
@ -39,32 +54,69 @@ class EquipeInline(admin.TabularInline):
class AnexosInline(admin.TabularInline): class AnexosInline(admin.TabularInline):
model = Anexo model = Anexo
extra = 2 extra = 2
exclude = ['data_pub', ] exclude = [
"data_pub",
]
class AnexoAdmin(BaseModelAdmin): class AnexoAdmin(BaseModelAdmin):
date_hierarchy = 'data_pub' date_hierarchy = "data_pub"
exclude = ['data_pub', ] exclude = [
list_display = ('arquivo', 'descricao', 'data_pub', 'diagnostico') "data_pub",
raw_id_fields = ('diagnostico',) ]
search_fields = ('descricao', 'diagnostico__id', 'arquivo', list_display = ("arquivo", "descricao", "data_pub", "diagnostico")
'diagnostico__casa_legislativa__nome') raw_id_fields = ("diagnostico",)
search_fields = (
"descricao",
"diagnostico__id",
"arquivo",
"diagnostico__casa_legislativa__nome",
)
class DiagnosticoAdmin(BaseEntityAdmin): class DiagnosticoAdmin(BaseEntityAdmin):
form = DiagnosticoForm form = DiagnosticoForm
actions = [publicar_diagnostico, despublicar_diagnostico] actions = [publicar_diagnostico, despublicar_diagnostico]
inlines = (EquipeInline, AnexosInline) inlines = (EquipeInline, AnexosInline)
search_fields = ('casa_legislativa__nome',) search_fields = ("casa_legislativa__nome",)
list_display = ('casa_legislativa', 'get_uf', 'data_visita_inicio', 'data_visita_fim', 'responsavel', 'publicado') list_display = (
list_filter = ('publicado', 'casa_legislativa__municipio__uf__nome', 'casa_legislativa', 'data_publicacao', 'data_visita_inicio', 'data_visita_fim') "casa_legislativa",
raw_id_fields = ('casa_legislativa',) "get_uf",
ordering = ('casa_legislativa',) "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 = ( 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',)}), "00. Identificação do Diagnóstico",
('02. Identificação de Competências da Casa Legislativa', {'fields': ()}) {
"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 # popula o eav fieldsets ordenando as categorias e as perguntas
@ -72,72 +124,94 @@ class DiagnosticoAdmin(BaseEntityAdmin):
try: try:
for categoria in Categoria.objects.all(): for categoria in Categoria.objects.all():
# ordena as perguntas pelo title e utiliza o name no fieldset # 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)] perguntas = [pergunta[1] for pergunta in sorted(perguntas_by_title)]
eav_fieldsets += ((categoria, { eav_fieldsets += (
'fields': tuple(perguntas), (
'classes': ['collapse'] categoria,
}),) {"fields": tuple(perguntas), "classes": ["collapse"]},
),
)
except OperationalError: except OperationalError:
pass # Hack to prevent Django.db.OperationalError on migrate/syncdb at creating new database pass # Hack to prevent Django.db.OperationalError on migrate/syncdb at creating new database
except ProgrammingError: except ProgrammingError:
pass # Hack to prevent Django.db.OperationalError on migrate/syncdb at creating new database pass # Hack to prevent Django.db.OperationalError on migrate/syncdb at creating new database
def get_uf(self, obj): def get_uf(self, obj):
return '%s' % (obj.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__nome' get_uf.short_description = _("UF")
get_uf.admin_order_field = "casa_legislativa__municipio__uf__nome"
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return super(DiagnosticoAdmin, self).lookup_allowed(lookup, value) or \ return super(DiagnosticoAdmin, self).lookup_allowed(
lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact'] lookup, value
) or lookup in ["casa_legislativa__municipio__uf__codigo_ibge__exact"]
def changelist_view(self, request, extra_context=None): def changelist_view(self, request, extra_context=None):
import re import re
request.GET._mutable = True request.GET._mutable = True
if 'data_visita_inicio__gte' in request.GET: if "data_visita_inicio__gte" in request.GET:
value = request.GET.get('data_visita_inicio__gte', '') value = request.GET.get("data_visita_inicio__gte", "")
if value == '': if value == "":
del request.GET['data_visita_inicio__gte'] del request.GET["data_visita_inicio__gte"]
elif re.match('^\d*$', value): # Year only elif re.match("^\d*$", value): # Year only
request.GET['data_visita_inicio__gte'] = "%s-01-01" % value # Complete with january 1st request.GET["data_visita_inicio__gte"] = (
elif re.match('^\d*\D\d*$', value): # Year and month "%s-01-01" % value
request.GET['data_visita_inicio__gte'] = '%s-01' % value # Complete with 1st day of month ) # Complete with january 1st
if 'data_visita_inicio__lte' in request.GET: elif re.match("^\d*\D\d*$", value): # Year and month
value = request.GET.get('data_visita_inicio__lte', '') request.GET["data_visita_inicio__gte"] = (
if value == '': "%s-01" % value
del request.GET['data_visita_inicio__lte'] ) # Complete with 1st day of month
elif re.match('^\d*$', value): # Year only if "data_visita_inicio__lte" in request.GET:
request.GET['data_visita_inicio__lte'] = "%s-01-01" % value # Complete with january 1st value = request.GET.get("data_visita_inicio__lte", "")
elif re.match('^\d*\D\d*$', value): # Year and month if value == "":
request.GET['data_visita_inicio__lte'] = '%s-01' % value # Complete with 1st day of month 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 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): class EscolhaAdmin(BaseModelAdmin):
search_fields = ('title',) search_fields = ("title",)
list_display = ('title', 'schema', 'schema_to_open') list_display = ("title", "schema", "schema_to_open")
raw_id_fields = ('schema', 'schema_to_open') raw_id_fields = ("schema", "schema_to_open")
ordering = ('schema', 'title') ordering = ("schema", "title")
class EscolhaInline(admin.TabularInline): class EscolhaInline(admin.TabularInline):
model = Escolha model = Escolha
fk_name = 'schema' fk_name = "schema"
raw_id_fields = ('schema_to_open',) raw_id_fields = ("schema_to_open",)
verbose_name = _('Escolhas (apenas para choices ou multiple choices)') verbose_name = _("Escolhas (apenas para choices ou multiple choices)")
extra = 0 extra = 0
class PerguntaAdmin(BaseSchemaAdmin): class PerguntaAdmin(BaseSchemaAdmin):
search_fields = ('title', 'help_text', 'name',) search_fields = (
list_display = ('title', 'categoria', 'datatype', 'help_text', 'required') "title",
list_filter = ('datatype', 'categoria', 'required') "help_text",
"name",
)
list_display = ("title", "categoria", "datatype", "help_text", "required")
list_filter = ("datatype", "categoria", "required")
inlines = (EscolhaInline,) inlines = (EscolhaInline,)
admin.site.register(Diagnostico, DiagnosticoAdmin) admin.site.register(Diagnostico, DiagnosticoAdmin)
admin.site.register(Pergunta, PerguntaAdmin) admin.site.register(Pergunta, PerguntaAdmin)
admin.site.register(Escolha, EscolhaAdmin) admin.site.register(Escolha, EscolhaAdmin)

9
sigi/apps/diagnosticos/decorators.py

@ -11,8 +11,10 @@ def validate_diagnostico(func):
ou o usuario nao seja um membro da equipe ou o usuario nao seja um membro da equipe
""" """
try: try:
diagnostico = Diagnostico.objects.filter(publicado=False).get(pk=id_diagnostico) diagnostico = Diagnostico.objects.filter(publicado=False).get(
if (request.user.servidor in diagnostico.membros): pk=id_diagnostico
)
if request.user.servidor in diagnostico.membros:
# continua o processamento normal da view # continua o processamento normal da view
return func(request, id_diagnostico, *args, **kwargs) return func(request, id_diagnostico, *args, **kwargs)
except Diagnostico.DoesNotExist: except Diagnostico.DoesNotExist:
@ -20,5 +22,6 @@ def validate_diagnostico(func):
# renderiza a pagina de 404 # renderiza a pagina de 404
context = RequestContext(request, {}) context = RequestContext(request, {})
return render_to_response('mobile/404.html', context) return render_to_response("mobile/404.html", context)
return decorator return decorator

156
sigi/apps/diagnosticos/forms.py

@ -3,9 +3,15 @@ from copy import deepcopy
from django import forms from django import forms
from django.contrib.contenttypes.generic import generic_inlineformset_factory from django.contrib.contenttypes.generic import generic_inlineformset_factory
from django.forms import (BooleanField, CharField, DateField, from django.forms import (
FloatField, ModelChoiceField, Textarea, BooleanField,
ModelMultipleChoiceField) CharField,
DateField,
FloatField,
ModelChoiceField,
Textarea,
ModelMultipleChoiceField,
)
from django.forms.forms import BoundField from django.forms.forms import BoundField
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from eav.fields import RangeField 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.casas.models import Orgao, Funcionario
from sigi.apps.contatos.models import Telefone from sigi.apps.contatos.models import Telefone
from sigi.apps.diagnosticos.models import Diagnostico 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): class DiagnosticoForm(BaseDynamicEntityForm):
@ -22,6 +31,7 @@ class DiagnosticoForm(BaseDynamicEntityForm):
"""Classe responsável por contruir o formulário, """Classe responsável por contruir o formulário,
vinculando ao modelo Diagnostico vinculando ao modelo Diagnostico
""" """
model = Diagnostico model = Diagnostico
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -29,7 +39,7 @@ class DiagnosticoForm(BaseDynamicEntityForm):
for k, f in self.fields.iteritems(): for k, f in self.fields.iteritems():
if isinstance(f, CharField): if isinstance(f, CharField):
f.widget = forms.widgets.Textarea(attrs={'cols': '80'}) f.widget = forms.widgets.Textarea(attrs={"cols": "80"})
class DiagnosticoMobileForm(BaseDynamicEntityForm): class DiagnosticoMobileForm(BaseDynamicEntityForm):
@ -41,36 +51,40 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
""" """
FIELD_CLASSES = { FIELD_CLASSES = {
'text': CharField, "text": CharField,
'float': FloatField, "float": FloatField,
'date': DateField, "date": DateField,
'bool': BooleanField, "bool": BooleanField,
'one': ModelChoiceField, "one": ModelChoiceField,
'many': ModelMultipleChoiceField, "many": ModelMultipleChoiceField,
'range': RangeField, "range": RangeField,
} }
FIELD_EXTRA = { FIELD_EXTRA = {
'one': {'widget': EavRadioSelect}, "one": {"widget": EavRadioSelect},
'many': {'widget': EavCheckboxSelectMultiple}, "many": {"widget": EavCheckboxSelectMultiple},
} }
FIELD_WIDGET = { FIELD_WIDGET = {
'consideracoes_gerais': {'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_parlamentares_da_camara_municipal": {
'descreva_5_cursos_prioritarios_para_treinamento_de_servidores_da_camara_municipal': {'widget': Textarea}, "widget": Textarea
'sugestoes_para_a_area_de_capacitacao': {'widget': Textarea}, },
'sugestoes_para_a_area_de_comunicacao': {'widget': Textarea}, "descreva_5_cursos_prioritarios_para_treinamento_de_servidores_da_camara_municipal": {
'sugestoes_para_a_area_de_informacao': {'widget': Textarea}, "widget": Textarea
'sugestoes_para_a_area_de_ti': {'widget': Textarea}, },
'inscricoes_para_lista_gitec': {'widget': Textarea}, "sugestoes_para_a_area_de_capacitacao": {"widget": Textarea},
'inscricoes_para_lista_gial': {'widget': Textarea}, "sugestoes_para_a_area_de_comunicacao": {"widget": Textarea},
'inscricoes_para_lista_gicom': {'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: class Meta:
model = Diagnostico model = Diagnostico
fields = '__all__' fields = "__all__"
def __init__(self, data=None, category=None, *args, **kwargs): def __init__(self, data=None, category=None, *args, **kwargs):
super(BaseDynamicEntityForm, self).__init__(data, *args, **kwargs) super(BaseDynamicEntityForm, self).__init__(data, *args, **kwargs)
@ -78,7 +92,9 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
def __iter__(self): def __iter__(self):
# ordena os campos do formulario usando o atributo label # 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): for label, name, field in sorted(fields_by_label):
yield BoundField(self, field, name) yield BoundField(self, field, name)
@ -90,7 +106,10 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
""" """
# Caso seja as duas primeiras categorias, utilize # Caso seja as duas primeiras categorias, utilize
# os campos do modelo # os campos do modelo
if int(category) in (0, 1, ): if int(category) in (
0,
1,
):
self.fields = deepcopy(self.base_fields) self.fields = deepcopy(self.base_fields)
else: else:
self.fields = dict() self.fields = dict()
@ -100,26 +119,34 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
for schema in self.instance.get_schemata(int(category)): for schema in self.instance.get_schemata(int(category)):
defaults = { defaults = {
'label': schema.title, "label": schema.title,
'required': schema.required, "required": schema.required,
'help_text': schema.help_text, "help_text": schema.help_text,
} }
datatype = schema.datatype datatype = schema.datatype
if datatype == schema.TYPE_MANY: if datatype == schema.TYPE_MANY:
choices = getattr(self.instance, schema.name) choices = getattr(self.instance, schema.name)
defaults.update({'queryset': schema.get_choices(), defaults.update(
'initial': [x.pk for x in choices]}) {
"queryset": schema.get_choices(),
"initial": [x.pk for x in choices],
}
)
elif datatype == schema.TYPE_ONE: elif datatype == schema.TYPE_ONE:
choice = getattr(self.instance, schema.name) choice = getattr(self.instance, schema.name)
defaults.update({'queryset': schema.get_choices(), defaults.update(
'initial': choice.pk if choice else None, {
"queryset": schema.get_choices(),
"initial": choice.pk if choice else None,
# if schema is required remove --------- from ui # if schema is required remove --------- from ui
'empty_label': None if schema.required else "---------"}) "empty_label": None if schema.required else "---------",
}
)
extra = self.FIELD_EXTRA.get(datatype, {}) extra = self.FIELD_EXTRA.get(datatype, {})
extra.update(self.FIELD_WIDGET.get(schema.name, {})) extra.update(self.FIELD_WIDGET.get(schema.name, {}))
if hasattr(extra, '__call__'): if hasattr(extra, "__call__"):
extra = extra(schema) extra = extra(schema)
defaults.update(extra) defaults.update(extra)
@ -128,28 +155,43 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
# fill initial data (if attribute was already defined) # fill initial data (if attribute was already defined)
value = getattr(self.instance, schema.name) 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 self.initial[schema.name] = value
class OrgaoMobileForm(forms.ModelForm): 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() data_criacao = forms.DateField()
class Meta: class Meta:
model = Orgao 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): def __init__(self, *args, **kwargs):
super(OrgaoMobileForm, self).__init__(*args, **kwargs) super(OrgaoMobileForm, self).__init__(*args, **kwargs)
self.fields['data_criacao'] = forms.DateField( self.fields["data_criacao"] = forms.DateField(
label=_('Data de criação do Município'), label=_("Data de criação do Município"),
initial=self.instance.municipio.data_criacao, initial=self.instance.municipio.data_criacao,
required=False) required=False,
)
def save(self, commit=True): def save(self, commit=True):
super(OrgaoMobileForm, self).save(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: if commit:
self.instance.municipio.save() self.instance.municipio.save()
return self.instance return self.instance
@ -160,18 +202,27 @@ class TelefoneMobileForm(forms.ModelForm):
class Meta: class Meta:
model = Telefone model = Telefone
fields = ('numero', 'tipo') fields = ("numero", "tipo")
class FuncionariosMobileForm(forms.ModelForm): 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): def __init__(self, data=None, prefix=None, instance=None, *args, **kwargs):
super(FuncionariosMobileForm, self).__init__(data, prefix=prefix, instance=instance, *args, **kwargs) super(FuncionariosMobileForm, self).__init__(
self.telefones = self.TelefoneFormSet(data, prefix=prefix, instance=instance) data, prefix=prefix, instance=instance, *args, **kwargs
)
self.telefones = self.TelefoneFormSet(
data, prefix=prefix, instance=instance
)
def is_valid(self): 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): def save(self, commit=True):
self.telefones.save(commit) self.telefones.save(commit)
@ -179,4 +230,11 @@ class FuncionariosMobileForm(forms.ModelForm):
class Meta: class Meta:
model = Funcionario model = Funcionario
fields = ('nome', 'email', 'cargo', 'funcao', 'tempo_de_servico', 'sexo') fields = (
"nome",
"email",
"cargo",
"funcao",
"tempo_de_servico",
"sexo",
)

832
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.contatos.models import UnidadeFederativa
from sigi.apps.diagnosticos.models import Categoria, Diagnostico, Resposta from sigi.apps.diagnosticos.models import Categoria, Diagnostico, Resposta
DATATYPES = { DATATYPES = {"text": "T", "float": "N", "date": "D", "one": "L", "many": "M"}
'text': 'T',
'float': 'N',
'date': 'D',
'one': 'L',
'many': 'M'
}
class Command(BaseCommand): class Command(BaseCommand):
help = """Exporta dados do diagnóstico para o formato Tab-Separated-Values help = """Exporta dados do diagnóstico para o formato Tab-Separated-Values
@ -22,155 +17,645 @@ class Command(BaseCommand):
def handle(self, *args, **options): def handle(self, *args, **options):
def normalize(l): 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:] nonum = lambda s: s[s.index(" ") + 1 :]
avalue = lambda e: ('Y' if e.title == 'Sim' else 'N' avalue = lambda e: (
if e.title == 'Não' else e.id) "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( setores = [
Funcionario.SETOR_CHOICES)] (i + 1, s[0], s[1]) for i, s in enumerate(Funcionario.SETOR_CHOICES)
]
if len(args) < 2: if len(args) < 2:
raise CommandError("Use: ls_export survey_id struct.txt data.csv") raise CommandError("Use: ls_export survey_id struct.txt data.csv")
survey_id = args[0] survey_id = args[0]
lsf = csv.writer(open(args[1], 'wb+'), delimiter="\t", lsf = csv.writer(
quoting=csv.QUOTE_MINIMAL) open(args[1], "wb+"), delimiter="\t", quoting=csv.QUOTE_MINIMAL
)
struct = ['id', 'token', 'submitdate', 'lastpage', 'startlanguage', struct = [
'seed'] "id",
"token",
"submitdate",
"lastpage",
"startlanguage",
"seed",
]
self.stdout.write("Exporting survey structure: ") self.stdout.write("Exporting survey structure: ")
# Structure headers # # Structure headers #
self.stdout.write("\tStructure headers...", ending=" ") self.stdout.write("\tStructure headers...", ending=" ")
lsf.writerow(['id', 'related_id', 'class', 'type/scale', 'name', lsf.writerow(
'relevance', 'text', 'help', 'language', 'validation', [
'mandatory', 'other', 'default', 'same_default']) "id",
lsf.writerows([ "related_id",
['', '', 'S', '', 'sid', '', survey_id], "class",
['', '', 'S', '', 'format', '', 'G'], "type/scale",
['', '', 'S', '', 'language', '', 'pt-BR'], "name",
['', '', 'SL', '', 'surveyls_survey_id', '', survey_id, '', "relevance",
'pt-BR'], "text",
['', '', 'SL', '', 'surveyls_language', '', 'pt-BR', '', 'pt-BR'], "help",
['', '', 'SL', '', 'surveyls_title', '', "language",
'Diagnóstico PML'.encode('utf-8'), '', 'pt-BR']]) "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!") self.stdout.write("Done!")
# Identificação da Casa Legislativa e sua equipe # # Identificação da Casa Legislativa e sua equipe #
self.stdout.write("\tIdentificação da Casa...", ending=" ") self.stdout.write("\tIdentificação da Casa...", ending=" ")
lsf.writerow(normalize(['1000', '', 'G', '', 'Identificação da Casa', lsf.writerow(
'', '', '', 'pt-BR'])) normalize(
lsf.writerow(normalize(['1001', '', 'Q', 'L', 'c001q001', '1', [
'Região', '', 'pt-BR', '', 'Y', 'N', '', '0'])) "1000",
struct.append('c001q001') "",
lsf.writerows([normalize(['1001', '', 'A', '0', sigla, '', nome, '', "G",
'pt-BR']) for sigla, nome in UnidadeFederativa.REGIAO_CHOICES]) "",
lsf.writerow(normalize(['1002', '', 'Q', '!', 'c001q002', '1', "Identificação da Casa",
'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()]) "pt-BR",
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', lsf.writerow(
'Data de criação do município', '', 'pt-BR', '', 'Y', 'N', '', normalize(
'0'])) [
struct.append('c001q004') "1001",
lsf.writerow(normalize(['1005', '', 'Q', 'S', 'c001q005', '1', "",
'Nome da Casa', '', 'pt-BR', '', 'Y', 'N', '', '0'])) "Q",
struct.append('c001q005') "L",
lsf.writerow(normalize(['1006', '', 'Q', 'D', 'c001q006', '1', "c001q001",
'Data de instalação do legislativo', '', 'pt-BR', '', 'Y', 'N', '', "1",
'0'])) "Região",
struct.append('c001q006') "",
lsf.writerow(normalize(['1007', '', 'Q', 'T', 'c001q007', '1', "pt-BR",
'Endereço', '', 'pt-BR', '', 'N', 'N', '', '0'])) "",
struct.append('c001q007') "Y",
lsf.writerow(normalize(['1008', '', 'Q', 'S', 'c001q008', '1', "N",
'CNPJ', '', 'pt-BR', '', 'N', 'N', '', '0'])) "",
struct.append('c001q008') "0",
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', struct.append("c001q001")
'Endereço Web', '', 'pt-BR', '', 'N', 'N', '', '0'])) lsf.writerows(
struct.append('c001q010') [
lsf.writerow(normalize(['1011', '', 'Q', ';', 'c001q011', '1', normalize(["1001", "", "A", "0", sigla, "", nome, "", "pt-BR"])
'Pessoas de contato', '', 'pt-BR', '', 'N', 'N', '', '0'])) for sigla, nome in UnidadeFederativa.REGIAO_CHOICES
lsf.writerow(normalize(['101198', '', 'SQ', '1', 'SQ00101', '', 'Nome', ]
'', 'pt-BR', '', '', 'N', '', '0'])) )
lsf.writerow(normalize(['101199', '', 'SQ', '1', 'SQ00102', '', lsf.writerow(
'E-mail', '', 'pt-BR', '', '', 'N', '', '0'])) 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: for i, k, v in setores:
lsf.writerow(normalize(['10110{0}'.format(i), '', 'SQ', '', lsf.writerow(
'SQ1010{0}'.format(i), '1', v, '', 'pt-BR', '', '', 'N', normalize(
'', '0'])) [
struct.extend([ "10110{0}".format(i),
'c001q011_SQ1010{0}_SQ00101'.format(i), "",
'c001q011_SQ1010{0}_SQ00102'.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!") self.stdout.write("Done!")
# Equipe de diagnóstico # # Equipe de diagnóstico #
self.stdout.write("\tEquipe de diagnóstico...", ending=" ") self.stdout.write("\tEquipe de diagnóstico...", ending=" ")
lsf.writerow(normalize(['2000', '', 'G', '', 'Equipe de diagnóstico', lsf.writerow(
'', '', '', 'pt-BR'])) normalize(
lsf.writerow(normalize(['2001', '', 'Q', 'D', 'c002q001', '1', [
'Data de início da visita', '', 'pt-BR', '', 'Y', 'N', '', '0'])) "2000",
struct.append('c002q001') "",
lsf.writerow(normalize(['2002', '', 'Q', 'D', 'c002q002', '1', "G",
'Data de término da visita', '', 'pt-BR', '', 'Y', 'N', '', '0'])) "",
struct.append('c002q002') "Equipe de diagnóstico",
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', "pt-BR",
'Membros da equipe', '', 'pt-BR', '', 'Y', 'N', '', '0'])) ]
struct.append('c002q004') )
)
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!") self.stdout.write("Done!")
for c in Categoria.objects.all(): for c in Categoria.objects.all():
self.stdout.write("\t{0}...".format(nonum(c.nome).encode('utf-8')), ending=" ") self.stdout.write(
lsf.writerow(normalize([str(c.id), '', 'G', '', "\t{0}...".format(nonum(c.nome).encode("utf-8")), ending=" "
nonum(c.nome), '', nonum(c.nome), '', )
'pt-BR'])) 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()]) perguntas = sorted([(p.title, p) for p in c.perguntas.all()])
for t, p in perguntas: for t, p in perguntas:
lstype = DATATYPES[p.datatype] lstype = DATATYPES[p.datatype]
# Hack para perguntas SIM/NÃO que foram cadastradas como Choice # Hack para perguntas SIM/NÃO que foram cadastradas como Choice
if lstype == 'L': if lstype == "L":
if ("".join([e.title for e in p.choices.all()]) in if "".join([e.title for e in p.choices.all()]) in [
["SimNão", "NãoSim"]): "SimNão",
lstype = 'Y' "NãoSim",
]:
lstype = "Y"
######## ########
relevance = "1" relevance = "1"
if p.abre_por.exists(): if p.abre_por.exists():
relevance = "(" + " or ".join( relevance = (
['({sid}X{gid}X{qid}.NAOK == "{value}")'.format( "("
sid=survey_id, gid=e.schema.categoria.id, + " or ".join(
qid=e.schema.id, value=avalue(e)) for e in [
p.abre_por.all()]) + ")" '({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, lsf.writerow(
'c{0:03}q{1:03}'.format(c.id, p.id), relevance, normalize(
nonum(p.title), p.help_text, 'pt-BR', '', 'NY'[p.required], [
'N', '', '0'])) str(p.id),
if lstype == 'L': "",
lsf.writerows([normalize([str(p.id), '', 'A', '0', "Q",
str(e.id), '', e.title, '', 'pt-BR']) lstype,
for e in p.choices.all()]) "c{0:03}q{1:03}".format(c.id, p.id),
if lstype == 'M': relevance,
lsf.writerows([normalize([str(p.id*1000+e.id), '', 'SQ', nonum(p.title),
'', str(e.id), '1', e.title, '', 'pt-BR']) p.help_text,
for e in p.choices.all()]) "pt-BR",
struct.extend(['c{0:03}q{1:03}_{2}'.format(c.id, p.id, "",
e.id) for e in p.choices.all()]) "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: 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!") self.stdout.write("Done!")
if len(args) < 3: # No data export if len(args) < 3: # No data export
@ -178,35 +663,38 @@ class Command(BaseCommand):
self.stdout.write("Exporting survey data: ") self.stdout.write("Exporting survey data: ")
dtf = csv.writer(open(args[2], 'wb+'), delimiter='\t', dtf = csv.writer(
quoting=csv.QUOTE_MINIMAL) open(args[2], "wb+"), delimiter="\t", quoting=csv.QUOTE_MINIMAL
)
dtf.writerow(struct) dtf.writerow(struct)
for d in Diagnostico.objects.all(): for d in Diagnostico.objects.all():
self.stdout.write("\t{0}".format(d.casa_legislativa.nome)) 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: if d.data_publicacao:
form['submitdate'] = d.data_publicacao.isoformat() form["submitdate"] = d.data_publicacao.isoformat()
# form['lastpage'] = '8' # form['lastpage'] = '8'
form['startlanguage'] = 'pt-BR' form["startlanguage"] = "pt-BR"
# form['seed'] = '123456' # form['seed'] = '123456'
# Identificação da Casa Legislativa e sua equipe # # Identificação da Casa Legislativa e sua equipe #
form['c001q001'] = d.casa_legislativa.municipio.uf.regiao form["c001q001"] = d.casa_legislativa.municipio.uf.regiao
form['c001q002'] = d.casa_legislativa.municipio.uf.sigla form["c001q002"] = d.casa_legislativa.municipio.uf.sigla
form['c001q003'] = d.casa_legislativa.municipio.nome form["c001q003"] = d.casa_legislativa.municipio.nome
if d.casa_legislativa.municipio.data_criacao: if d.casa_legislativa.municipio.data_criacao:
form['c001q004'] = \ form[
d.casa_legislativa.municipio.data_criacao.isoformat() "c001q004"
form['c001q005'] = d.casa_legislativa.nome ] = d.casa_legislativa.municipio.data_criacao.isoformat()
form["c001q005"] = d.casa_legislativa.nome
if d.casa_legislativa.data_instalacao: if d.casa_legislativa.data_instalacao:
form['c001q006'] = \ form[
d.casa_legislativa.data_instalacao.isoformat() "c001q006"
form['c001q007'] = ( ] = d.casa_legislativa.data_instalacao.isoformat()
form["c001q007"] = (
"{logradouro}{{cr}}{{newline}}" "{logradouro}{{cr}}{{newline}}"
"{bairro}{{cr}}{{newline}}" "{bairro}{{cr}}{{newline}}"
"{cep} - {municipio} - {uf}".format( "{cep} - {municipio} - {uf}".format(
@ -214,62 +702,64 @@ class Command(BaseCommand):
bairro=d.casa_legislativa.bairro, bairro=d.casa_legislativa.bairro,
cep=d.casa_legislativa.cep, cep=d.casa_legislativa.cep,
municipio=d.casa_legislativa.municipio.nome, municipio=d.casa_legislativa.municipio.nome,
uf=d.casa_legislativa.municipio.uf.sigla uf=d.casa_legislativa.municipio.uf.sigla,
)) )
form['c001q008'] = d.casa_legislativa.cnpj )
form['c001q009'] = d.casa_legislativa.email form["c001q008"] = d.casa_legislativa.cnpj
form['c001q010'] = d.casa_legislativa.pagina_web form["c001q009"] = d.casa_legislativa.email
form["c001q010"] = d.casa_legislativa.pagina_web
for i, k, v in setores: for i, k, v in setores:
q = d.casa_legislativa.funcionario_set.filter(setor=k) q = d.casa_legislativa.funcionario_set.filter(setor=k)
if q.exists(): if q.exists():
f = q.first() f = q.first()
knome = 'c001q011_SQ1010{0}_SQ00101'.format(i) knome = "c001q011_SQ1010{0}_SQ00101".format(i)
kmail = 'c001q011_SQ1010{0}_SQ00102'.format(i) kmail = "c001q011_SQ1010{0}_SQ00102".format(i)
form[knome] = f.nome form[knome] = f.nome
form[kmail] = f.email form[kmail] = f.email
if d.data_visita_inicio: if d.data_visita_inicio:
form['c002q001'] = d.data_visita_inicio.isoformat() form["c002q001"] = d.data_visita_inicio.isoformat()
if d.data_visita_fim: if d.data_visita_fim:
form['c002q002'] = d.data_visita_fim.isoformat() form["c002q002"] = d.data_visita_fim.isoformat()
form['c002q003'] = d.responsavel.nome_completo form["c002q003"] = d.responsavel.nome_completo
form['c002q004'] = "{cr}{newline}".join( form["c002q004"] = "{cr}{newline}".join(
[e.membro.nome_completo for e in d.equipe_set.all()]) [e.membro.nome_completo for e in d.equipe_set.all()]
)
for r in Resposta.objects.filter(entity_id=d.id): 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( key = "c{cid:03}q{qid:03}_{sqid}".format(
cid=r.schema.categoria.id, cid=r.schema.categoria.id,
qid=r.schema.id, qid=r.schema.id,
sqid=r.value.id sqid=r.value.id,
) )
value = 'Y' value = "Y"
else: else:
key = "c{cid:03}q{qid:03}".format(cid=r.schema.categoria.id, key = "c{cid:03}q{qid:03}".format(
qid=r.schema.id) cid=r.schema.categoria.id, qid=r.schema.id
)
value = r.value value = r.value
if r.schema.datatype == 'one': if r.schema.datatype == "one":
if value is None: if value is None:
value = '{question_not_shown}' value = "{question_not_shown}"
elif value.title == 'Sim': elif value.title == "Sim":
value = 'Y' value = "Y"
elif value.title == 'Não': elif value.title == "Não":
value = 'N' value = "N"
else: else:
value = r.value.id value = r.value.id
elif r.schema.datatype == 'text': elif r.schema.datatype == "text":
value = value.\ value = (
replace('\r\n', '{cr}{newline}').\ value.replace("\r\n", "{cr}{newline}")
replace('\r', '{cr}{newline}').\ .replace("\r", "{cr}{newline}")
replace('\n', '{cr}{newline}').\ .replace("\n", "{cr}{newline}")
replace('\t', ' ') .replace("\t", " ")
)
if value is None: if value is None:
value = '{question_not_shown}' value = "{question_not_shown}"
form[key] = '{0}'.format(value) form[key] = "{0}".format(value)
dtf.writerow(normalize(form.values())) dtf.writerow(normalize(form.values()))
self.stdout.write('Done!') self.stdout.write("Done!")

349
sigi/apps/diagnosticos/migrations/0001_initial.py

@ -10,139 +10,340 @@ import sigi.apps.utils
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0001_initial'), ("servidores", "0001_initial"),
('contenttypes', '0001_initial'), ("contenttypes", "0001_initial"),
('casas', '0001_initial'), ("casas", "0001_initial"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Anexo', name="Anexo",
fields=[ 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')), "id",
('descricao', models.CharField(max_length=b'70', verbose_name='descri\xe7\xe3o')), models.AutoField(
('data_pub', models.DateTimeField(default=datetime.datetime.now, verbose_name='data da publica\xe7\xe3o do anexo')), 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={ options={
'ordering': ('-data_pub',), "ordering": ("-data_pub",),
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Categoria', name="Categoria",
fields=[ 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={ options={
'ordering': ('nome',), "ordering": ("nome",),
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Diagnostico', name="Diagnostico",
fields=[ 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)), "id",
('data_visita_inicio', models.DateField(null=True, verbose_name='data inicial da visita', blank=True)), models.AutoField(
('data_visita_fim', models.DateField(null=True, verbose_name='data final da visita', blank=True)), verbose_name="ID",
('publicado', models.BooleanField(default=False)), serialize=False,
('data_publicacao', models.DateField(null=True, verbose_name='data de publica\xe7\xe3o do diagn\xf3stico', blank=True)), auto_created=True,
('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa')), primary_key=True,
('responsavel', models.ForeignKey(verbose_name='respons\xe1vel', to='servidores.Servidor')), ),
),
(
"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={ options={
'verbose_name': 'diagn\xf3stico', "verbose_name": "diagn\xf3stico",
'verbose_name_plural': 'diagn\xf3sticos', "verbose_name_plural": "diagn\xf3sticos",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Equipe', name="Equipe",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('diagnostico', models.ForeignKey(to='diagnosticos.Diagnostico')), "id",
('membro', models.ForeignKey(to='servidores.Servidor')), 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={ options={
'verbose_name': 'equipe', "verbose_name": "equipe",
'verbose_name_plural': 'equipe', "verbose_name_plural": "equipe",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Escolha', name="Escolha",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('title', models.CharField(max_length=100)), "id",
('ordem', models.PositiveIntegerField(null=True, blank=True)), 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={ options={
'ordering': ('schema', 'ordem'), "ordering": ("schema", "ordem"),
'verbose_name': 'escolha', "verbose_name": "escolha",
'verbose_name_plural': 'escolhas', "verbose_name_plural": "escolhas",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Pergunta', name="Pergunta",
fields=[ 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')), "id",
('name', autoslug.fields.AutoSlugField(max_length=250, verbose_name='name', blank=True)), models.AutoField(
('help_text', models.CharField(help_text='short description for administrator', max_length=250, verbose_name='help text', blank=True)), verbose_name="ID",
('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')])), serialize=False,
('required', models.BooleanField(default=False, verbose_name='required')), auto_created=True,
('searched', models.BooleanField(default=False, verbose_name='include in search')), primary_key=True,
('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')), (
"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={ options={
'ordering': ('title',), "ordering": ("title",),
'verbose_name': 'pergunta', "verbose_name": "pergunta",
'verbose_name_plural': 'perguntas', "verbose_name_plural": "perguntas",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Resposta', name="Resposta",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('entity_id', models.IntegerField()), "id",
('value_text', models.TextField(null=True, blank=True)), models.AutoField(
('value_float', models.FloatField(null=True, blank=True)), verbose_name="ID",
('value_date', models.DateField(null=True, blank=True)), serialize=False,
('value_bool', models.NullBooleanField()), auto_created=True,
('value_range_min', models.FloatField(null=True, blank=True)), primary_key=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')), ("entity_id", models.IntegerField()),
('schema', models.ForeignKey(related_name=b'attrs', verbose_name='pergunta', to='diagnosticos.Pergunta')), ("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={ options={
'verbose_name': 'resposta', "verbose_name": "resposta",
'verbose_name_plural': 'respostas', "verbose_name_plural": "respostas",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.AddField( migrations.AddField(
model_name='escolha', model_name="escolha",
name='schema', name="schema",
field=models.ForeignKey(related_name=b'choices', verbose_name='pergunta', to='diagnosticos.Pergunta'), field=models.ForeignKey(
related_name=b"choices",
verbose_name="pergunta",
to="diagnosticos.Pergunta",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='escolha', model_name="escolha",
name='schema_to_open', name="schema_to_open",
field=models.ForeignKey(related_name=b'', verbose_name='pergunta para abrir', blank=True, to='diagnosticos.Pergunta', null=True), field=models.ForeignKey(
related_name=b"",
verbose_name="pergunta para abrir",
blank=True,
to="diagnosticos.Pergunta",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='anexo', model_name="anexo",
name='diagnostico', name="diagnostico",
field=models.ForeignKey(verbose_name='diagn\xf3stico', to='diagnosticos.Diagnostico'), field=models.ForeignKey(
verbose_name="diagn\xf3stico", to="diagnosticos.Diagnostico"
),
preserve_default=True, preserve_default=True,
), ),
] ]

15
sigi/apps/diagnosticos/migrations/0002_auto_20160719_0920.py

@ -9,14 +9,21 @@ import eav.models
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('diagnosticos', '0001_initial'), ("diagnosticos", "0001_initial"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='pergunta', model_name="pergunta",
name='name', 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), 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, preserve_default=True,
), ),
] ]

15
sigi/apps/diagnosticos/migrations/0002_auto_20170407_1024.py

@ -9,14 +9,21 @@ import eav.models
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('diagnosticos', '0001_initial'), ("diagnosticos", "0001_initial"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='pergunta', model_name="pergunta",
name='name', 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), 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, preserve_default=True,
), ),
] ]

14
sigi/apps/diagnosticos/migrations/0003_auto_20201101_2240.py

@ -7,14 +7,20 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('diagnosticos', '0002_auto_20170407_1024'), ("diagnosticos", "0002_auto_20170407_1024"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='escolha', model_name="escolha",
name='schema_to_open', name="schema_to_open",
field=models.ForeignKey(related_name='abre_por', verbose_name='pergunta para abrir', blank=True, to='diagnosticos.Pergunta', null=True), field=models.ForeignKey(
related_name="abre_por",
verbose_name="pergunta para abrir",
blank=True,
to="diagnosticos.Pergunta",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
] ]

12
sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py

@ -7,15 +7,17 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('diagnosticos', '0003_auto_20201101_2240'), ("diagnosticos", "0003_auto_20201101_2240"),
('casas', '0014_auto_20210406_1945'), ("casas", "0014_auto_20210406_1945"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='diagnostico', model_name="diagnostico",
name='casa_legislativa', name="casa_legislativa",
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'), field=models.ForeignKey(
verbose_name="Casa Legislativa", to="casas.Orgao"
),
preserve_default=True, preserve_default=True,
), ),
] ]

67
sigi/apps/diagnosticos/migrations/0005_auto_20210416_0841.py

@ -8,44 +8,73 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('diagnosticos', '0004_auto_20210406_1945'), ("diagnosticos", "0004_auto_20210406_1945"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='diagnostico', model_name="diagnostico",
name='casa_legislativa', name="casa_legislativa",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Casa Legislativa', to='casas.Orgao'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Casa Legislativa",
to="casas.Orgao",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='diagnostico', model_name="diagnostico",
name='responsavel', name="responsavel",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='respons\xe1vel', to='servidores.Servidor'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="respons\xe1vel",
to="servidores.Servidor",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='equipe', model_name="equipe",
name='membro', name="membro",
field=models.ForeignKey(to='servidores.Servidor', on_delete=django.db.models.deletion.PROTECT), field=models.ForeignKey(
to="servidores.Servidor",
on_delete=django.db.models.deletion.PROTECT,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='escolha', model_name="escolha",
name='schema_to_open', 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), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='resposta', model_name="resposta",
name='choice', name="choice",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='escolha', blank=True, to='diagnosticos.Escolha', null=True), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="escolha",
blank=True,
to="diagnosticos.Escolha",
null=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='resposta', model_name="resposta",
name='schema', name="schema",
field=models.ForeignKey(related_name='attrs', on_delete=django.db.models.deletion.PROTECT, verbose_name='pergunta', to='diagnosticos.Pergunta'), field=models.ForeignKey(
related_name="attrs",
on_delete=django.db.models.deletion.PROTECT,
verbose_name="pergunta",
to="diagnosticos.Pergunta",
),
preserve_default=True, preserve_default=True,
), ),
] ]

7
sigi/apps/diagnosticos/migrations/0006_merge.py

@ -7,9 +7,8 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('diagnosticos', '0002_auto_20160719_0920'), ("diagnosticos", "0002_auto_20160719_0920"),
('diagnosticos', '0005_auto_20210416_0841'), ("diagnosticos", "0005_auto_20210416_0841"),
] ]
operations = [ operations = []
]

153
sigi/apps/diagnosticos/models.py

@ -13,41 +13,42 @@ class Diagnostico(BaseEntity):
"""Modelo para representar unm diagnostico realizado """Modelo para representar unm diagnostico realizado
em uma Casa Legislativa em uma Casa Legislativa
""" """
casa_legislativa = models.ForeignKey( casa_legislativa = models.ForeignKey(
'casas.Orgao', "casas.Orgao",
on_delete=models.PROTECT, on_delete=models.PROTECT,
verbose_name=_('Casa Legislativa') verbose_name=_("Casa Legislativa"),
) )
# campo de busca em caixa baixa e sem acento # 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_uf_filter = True
# casa_legislativa.casa_tipo_filter = True # casa_legislativa.casa_tipo_filter = True
data_visita_inicio = models.DateField( data_visita_inicio = models.DateField(
'data inicial da visita', "data inicial da visita",
null=True, null=True,
blank=True, blank=True,
) )
data_visita_fim = models.DateField( data_visita_fim = models.DateField(
'data final da visita', "data final da visita",
null=True, null=True,
blank=True, blank=True,
) )
publicado = models.BooleanField(default=False) publicado = models.BooleanField(default=False)
data_publicacao = models.DateField( data_publicacao = models.DateField(
'data de publicação do diagnóstico', "data de publicação do diagnóstico",
null=True, null=True,
blank=True, blank=True,
) )
responsavel = models.ForeignKey( responsavel = models.ForeignKey(
'servidores.Servidor', "servidores.Servidor",
on_delete=models.PROTECT, on_delete=models.PROTECT,
verbose_name=_('responsável') verbose_name=_("responsável"),
) )
class Meta: class Meta:
verbose_name, verbose_name_plural = _('diagnóstico'), _('diagnósticos') verbose_name, verbose_name_plural = _("diagnóstico"), _("diagnósticos")
@property @property
def membros(self): def membros(self):
@ -72,7 +73,9 @@ class Diagnostico(BaseEntity):
ao menos uma resposta ao menos uma resposta
""" """
# unifica as categorias das perguntas dessas respostas # 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) return list(categoria_com_respostas)
@ -90,16 +93,19 @@ class Diagnostico(BaseEntity):
* host - O Host do sistema, para ser usado na * host - O Host do sistema, para ser usado na
construção do endereço do diagnóstico construção do endereço do diagnóstico
""" """
enviar_email(from_email, _("Diagnóstico publicado"), enviar_email(
'diagnosticos/email_diagnostico_publicado.txt', from_email,
_("Diagnóstico publicado"),
"diagnosticos/email_diagnostico_publicado.txt",
{ {
'responsavel': self.responsavel.nome_completo, "responsavel": self.responsavel.nome_completo,
'casa_legislativa': self.casa_legislativa, "casa_legislativa": self.casa_legislativa,
'data_diagnostico': self.data_visita_inicio, "data_diagnostico": self.data_visita_inicio,
'host': host, "host": host,
'url_diagnostico': self.get_absolute_url(), "url_diagnostico": self.get_absolute_url(),
'status': _("Publicado"), "status": _("Publicado"),
}) },
)
def email_diagnostico_alterado(self, from_email, host): def email_diagnostico_alterado(self, from_email, host):
"""Enviando email quando o status do diagnóstico """Enviando email quando o status do diagnóstico
@ -108,20 +114,22 @@ class Diagnostico(BaseEntity):
* host - O Host do sistema, para ser usado na * host - O Host do sistema, para ser usado na
construção do endereço do diagnóstico construção do endereço do diagnóstico
""" """
enviar_email(from_email, _("Diagnóstico alterado"), enviar_email(
'diagnosticos/email_diagnostico_alterado.txt', from_email,
_("Diagnóstico alterado"),
"diagnosticos/email_diagnostico_alterado.txt",
{ {
'servidor': self.responsavel.nome_completo, "servidor": self.responsavel.nome_completo,
'casa_legislativa': self.casa_legislativa, "casa_legislativa": self.casa_legislativa,
'data_diagnostico': self.data_visita_inicio, "data_diagnostico": self.data_visita_inicio,
'host': host, "host": host,
'url_diagnostico': self.get_absolute_url(), "url_diagnostico": self.get_absolute_url(),
'status': _("Alterado"), "status": _("Alterado"),
}) },
)
def get_schemata(self, category=None, *args, **kwargs): 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) schemas = super(Diagnostico, self).get_schemata(*args, **kwargs)
if category: if category:
schemas = [s for s in schemas if s.categoria_id == category] schemas = [s for s in schemas if s.categoria_id == category]
@ -134,7 +142,7 @@ class Diagnostico(BaseEntity):
return Pergunta.objects.all() return Pergunta.objects.all()
def __unicode__(self): def __unicode__(self):
return str(self.casa_legislativa).decode('utf8') return str(self.casa_legislativa).decode("utf8")
def get_absolute_url(self): def get_absolute_url(self):
return "/diagnosticos/diagnostico/%i.pdf" % (self.id,) return "/diagnosticos/diagnostico/%i.pdf" % (self.id,)
@ -145,10 +153,11 @@ 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 e sua ordem na hora de exibir no formulário
""" """
nome = models.CharField(max_length=255) nome = models.CharField(max_length=255)
class Meta: class Meta:
ordering = ('nome',) ordering = ("nome",)
def __unicode__(self): def __unicode__(self):
return self.nome return self.nome
@ -161,22 +170,25 @@ class Pergunta(BaseSchema):
Uma pergunta tem o nome e o tipo da resposta Uma pergunta tem o nome e o tipo da resposta
""" """
categoria = models.ForeignKey( categoria = models.ForeignKey(
Categoria, Categoria, on_delete=models.CASCADE, related_name="perguntas"
on_delete=models.CASCADE,
related_name='perguntas'
) )
def group_choices(self): def group_choices(self):
from django.db import connection, transaction from django.db import connection, transaction
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(""" cursor.execute(
"""
SELECT choice_id, sum(1) SELECT choice_id, sum(1)
FROM diagnosticos_resposta FROM diagnosticos_resposta
WHERE schema_id=%s and choice_id is not null WHERE schema_id=%s and choice_id is not null
GROUP BY choice_id; GROUP BY choice_id;
""", [self.id]) """,
[self.id],
)
return [ return [
(Escolha.objects.get(id=int(row[0])), row[1]) (Escolha.objects.get(id=int(row[0])), row[1])
@ -185,19 +197,23 @@ class Pergunta(BaseSchema):
def total_anwsers(self): def total_anwsers(self):
from django.db import connection, transaction from django.db import connection, transaction
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(""" cursor.execute(
"""
SELECT sum(1) SELECT sum(1)
FROM diagnosticos_resposta FROM diagnosticos_resposta
WHERE schema_id=%s WHERE schema_id=%s
""", [self.id]) """,
[self.id],
)
return cursor.fetchone() return cursor.fetchone()
class Meta: class Meta:
ordering = ('title',) ordering = ("title",)
verbose_name, verbose_name_plural = _('pergunta'), _('perguntas') verbose_name, verbose_name_plural = _("pergunta"), _("perguntas")
class Escolha(BaseChoice): class Escolha(BaseChoice):
@ -205,25 +221,26 @@ class Escolha(BaseChoice):
"""Perguntas de multiplas escolhas tem as opções """Perguntas de multiplas escolhas tem as opções
cadastradas neste modelo cadastradas neste modelo
""" """
schema = models.ForeignKey( schema = models.ForeignKey(
Pergunta, Pergunta,
on_delete=models.CASCADE, on_delete=models.CASCADE,
related_name='choices', related_name="choices",
verbose_name=_('pergunta') verbose_name=_("pergunta"),
) )
schema_to_open = models.ForeignKey( schema_to_open = models.ForeignKey(
Pergunta, Pergunta,
on_delete=models.SET_NULL, on_delete=models.SET_NULL,
related_name='abre_por', related_name="abre_por",
verbose_name=_('pergunta para abrir'), verbose_name=_("pergunta para abrir"),
blank=True, blank=True,
null=True null=True,
) )
ordem = models.PositiveIntegerField(blank=True, null=True) ordem = models.PositiveIntegerField(blank=True, null=True)
class Meta: class Meta:
ordering = ('schema', 'ordem') ordering = ("schema", "ordem")
verbose_name, verbose_name_plural = _('escolha'), _('escolhas') verbose_name, verbose_name_plural = _("escolha"), _("escolhas")
class Resposta(BaseAttribute): class Resposta(BaseAttribute):
@ -231,36 +248,34 @@ class Resposta(BaseAttribute):
"""Modelo para guardar as respostas das perguntas """Modelo para guardar as respostas das perguntas
de um diagnosico de um diagnosico
""" """
schema = models.ForeignKey( schema = models.ForeignKey(
Pergunta, Pergunta,
on_delete=models.PROTECT, on_delete=models.PROTECT,
related_name='attrs', related_name="attrs",
verbose_name=_('pergunta') verbose_name=_("pergunta"),
) )
choice = models.ForeignKey( choice = models.ForeignKey(
Escolha, Escolha,
on_delete=models.PROTECT, on_delete=models.PROTECT,
verbose_name=_('escolha'), verbose_name=_("escolha"),
blank=True, blank=True,
null=True null=True,
) )
class Meta: class Meta:
verbose_name, verbose_name_plural = _('resposta'), _('respostas') verbose_name, verbose_name_plural = _("resposta"), _("respostas")
class Equipe(models.Model): 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) diagnostico = models.ForeignKey(Diagnostico, on_delete=models.CASCADE)
membro = models.ForeignKey( membro = models.ForeignKey("servidores.Servidor", on_delete=models.PROTECT)
'servidores.Servidor',
on_delete=models.PROTECT
)
class Meta: class Meta:
verbose_name, verbose_name_plural = _('equipe'), _('equipe') verbose_name, verbose_name_plural = _("equipe"), _("equipe")
def __unicode__(self): def __unicode__(self):
return self.membro.__unicode__() return self.membro.__unicode__()
@ -271,18 +286,20 @@ 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. no processo de diagnóstico. Podem ser fotos, contratos, etc.
""" """
diagnostico = models.ForeignKey( diagnostico = models.ForeignKey(
Diagnostico, Diagnostico, on_delete=models.CASCADE, verbose_name="diagnóstico"
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: class Meta:
ordering = ('-data_pub',) ordering = ("-data_pub",)
def __unicode__(self): def __unicode__(self):
return unicode(self.arquivo.name) return unicode(self.arquivo.name)

68
sigi/apps/diagnosticos/templatetags/smart_if.py

@ -17,8 +17,8 @@ register = template.Library()
# Calculation objects # Calculation objects
# ============================================================================== # ==============================================================================
class BaseCalc(object):
class BaseCalc(object):
def __init__(self, var1, var2=None, negate=False): def __init__(self, var1, var2=None, negate=False):
self.var1 = var1 self.var1 = var1
self.var2 = var2 self.var2 = var2
@ -43,54 +43,48 @@ class BaseCalc(object):
class Or(BaseCalc): class Or(BaseCalc):
def calculate(self, var1, var2): def calculate(self, var1, var2):
return var1 or var2 return var1 or var2
class And(BaseCalc): class And(BaseCalc):
def calculate(self, var1, var2): def calculate(self, var1, var2):
return var1 and var2 return var1 and var2
class Equals(BaseCalc): class Equals(BaseCalc):
def calculate(self, var1, var2): def calculate(self, var1, var2):
return var1 == var2 return var1 == var2
class Greater(BaseCalc): class Greater(BaseCalc):
def calculate(self, var1, var2): def calculate(self, var1, var2):
return var1 > var2 return var1 > var2
class GreaterOrEqual(BaseCalc): class GreaterOrEqual(BaseCalc):
def calculate(self, var1, var2): def calculate(self, var1, var2):
return var1 >= var2 return var1 >= var2
class In(BaseCalc): class In(BaseCalc):
def calculate(self, var1, var2): def calculate(self, var1, var2):
return var1 in var2 return var1 in var2
OPERATORS = { OPERATORS = {
'=': (Equals, True), "=": (Equals, True),
'==': (Equals, True), "==": (Equals, True),
'!=': (Equals, False), "!=": (Equals, False),
'>': (Greater, True), ">": (Greater, True),
'>=': (GreaterOrEqual, True), ">=": (GreaterOrEqual, True),
'<=': (Greater, False), "<=": (Greater, False),
'<': (GreaterOrEqual, False), "<": (GreaterOrEqual, False),
'or': (Or, True), "or": (Or, True),
'and': (And, True), "and": (And, True),
'in': (In, True), "in": (In, True),
} }
BOOL_OPERATORS = ('or', 'and') BOOL_OPERATORS = ("or", "and")
class IfParser(object): class IfParser(object):
@ -111,7 +105,7 @@ class IfParser(object):
def parse(self): def parse(self):
if self.at_end(): if self.at_end():
raise self.error_class('No variables provided.') raise self.error_class("No variables provided.")
var1 = self.get_bool_var() var1 = self.get_bool_var()
while not self.at_end(): while not self.at_end():
op, negate = self.get_operator() op, negate = self.get_operator()
@ -123,7 +117,7 @@ class IfParser(object):
negate = True negate = True
token = None token = None
pos = self.pos pos = self.pos
while token is None or token == 'not': while token is None or token == "not":
if pos >= self.len: if pos >= self.len:
if eof_message is None: if eof_message is None:
raise self.error_class() raise self.error_class()
@ -152,28 +146,32 @@ class IfParser(object):
var = self.get_var() var = self.get_var()
if not self.at_end(): if not self.at_end():
op_token = self.get_token(lookahead=True)[0] op_token = self.get_token(lookahead=True)[0]
if isinstance(op_token, basestring) and (op_token not in if isinstance(op_token, basestring) and (
BOOL_OPERATORS): op_token not in BOOL_OPERATORS
):
op, negate = self.get_operator() op, negate = self.get_operator()
return op(var, self.get_var(), negate=negate) return op(var, self.get_var(), negate=negate)
return var return var
def get_var(self): def get_var(self):
token, negate = self.get_token('Reached end of statement, still ' token, negate = self.get_token(
'expecting a variable.') "Reached end of statement, still " "expecting a variable."
)
if isinstance(token, basestring) and token in OPERATORS: if isinstance(token, basestring) and token in OPERATORS:
raise self.error_class('Expected variable, got operator (%s).' % raise self.error_class(
token) "Expected variable, got operator (%s)." % token
)
var = self.create_var(token) var = self.create_var(token)
if negate: if negate:
return Or(var, negate=True) return Or(var, negate=True)
return var return var
def get_operator(self): def get_operator(self):
token, negate = self.get_token('Reached end of statement, still ' token, negate = self.get_token(
'expecting an operator.') "Reached end of statement, still " "expecting an operator."
)
if not isinstance(token, basestring) or token not in OPERATORS: 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(): if self.at_end():
raise self.error_class('No variable provided after "%s".' % token) raise self.error_class('No variable provided after "%s".' % token)
op, true = OPERATORS[token] op, true = OPERATORS[token]
@ -186,6 +184,7 @@ class IfParser(object):
# Actual templatetag code. # Actual templatetag code.
# ============================================================================== # ==============================================================================
class TemplateIfParser(IfParser): class TemplateIfParser(IfParser):
error_class = template.TemplateSyntaxError error_class = template.TemplateSyntaxError
@ -198,7 +197,6 @@ class TemplateIfParser(IfParser):
class SmartIfNode(template.Node): class SmartIfNode(template.Node):
def __init__(self, var, nodelist_true, nodelist_false=None): def __init__(self, var, nodelist_true, nodelist_false=None):
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
self.var = var self.var = var
@ -208,7 +206,7 @@ class SmartIfNode(template.Node):
return self.nodelist_true.render(context) return self.nodelist_true.render(context)
if self.nodelist_false: if self.nodelist_false:
return self.nodelist_false.render(context) return self.nodelist_false.render(context)
return '' return ""
def __repr__(self): def __repr__(self):
return "<Smart If node>" return "<Smart If node>"
@ -230,7 +228,7 @@ class SmartIfNode(template.Node):
return nodes return nodes
@register.tag('if') @register.tag("if")
def smart_if(parser, token): def smart_if(parser, token):
""" """
A smarter {% if %} tag for django templates. A smarter {% if %} tag for django templates.
@ -249,10 +247,10 @@ def smart_if(parser, token):
""" """
bits = token.split_contents()[1:] bits = token.split_contents()[1:]
var = TemplateIfParser(parser, bits).parse() var = TemplateIfParser(parser, bits).parse()
nodelist_true = parser.parse(('else', 'endif')) nodelist_true = parser.parse(("else", "endif"))
token = parser.next_token() token = parser.next_token()
if token.contents == 'else': if token.contents == "else":
nodelist_false = parser.parse(('endif',)) nodelist_false = parser.parse(("endif",))
parser.delete_first_token() parser.delete_first_token()
else: else:
nodelist_false = None nodelist_false = None

52
sigi/apps/diagnosticos/templatetags/test_smart_if.py

@ -19,7 +19,6 @@ class TestVar(object):
class TestIfParser(IfParser): class TestIfParser(IfParser):
def create_var(self, value): def create_var(self, value):
return TestVar(value) return TestVar(value)
@ -27,6 +26,7 @@ class TestIfParser(IfParser):
class ValueHolder(object): class ValueHolder(object):
pass pass
VALORES = ValueHolder() VALORES = ValueHolder()
VALORES.true = TestVar(True) VALORES.true = TestVar(True)
VALORES.false = TestVar(False) VALORES.false = TestVar(False)
@ -100,67 +100,67 @@ def test_parse_bits():
var = TestIfParser([False]).parse() var = TestIfParser([False]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser([False, 'or', True]).parse() var = TestIfParser([False, "or", True]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([False, 'and', True]).parse() var = TestIfParser([False, "and", True]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser(['not', False, 'and', 'not', False]).parse() var = TestIfParser(["not", False, "and", "not", False]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser(['not', 'not', True]).parse() var = TestIfParser(["not", "not", True]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([1, '=', 1]).parse() var = TestIfParser([1, "=", 1]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([1, 'not', '=', 1]).parse() var = TestIfParser([1, "not", "=", 1]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser([1, 'not', 'not', '=', 1]).parse() var = TestIfParser([1, "not", "not", "=", 1]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([1, '!=', 1]).parse() var = TestIfParser([1, "!=", 1]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser([3, '>', 2]).parse() var = TestIfParser([3, ">", 2]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([1, '<', 2]).parse() var = TestIfParser([1, "<", 2]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([2, 'not', 'in', [2, 3]]).parse() var = TestIfParser([2, "not", "in", [2, 3]]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser([1, 'or', 1, '=', 2]).parse() var = TestIfParser([1, "or", 1, "=", 2]).parse()
assert var.resolve({}) assert var.resolve({})
def test_boolean(): def test_boolean():
var = TestIfParser([True, 'and', True, 'and', True]).parse() var = TestIfParser([True, "and", True, "and", True]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([False, 'or', False, 'or', True]).parse() var = TestIfParser([False, "or", False, "or", True]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([True, 'and', False, 'or', True]).parse() var = TestIfParser([True, "and", False, "or", True]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([False, 'or', True, 'and', True]).parse() var = TestIfParser([False, "or", True, "and", True]).parse()
assert var.resolve({}) assert var.resolve({})
var = TestIfParser([True, 'and', True, 'and', False]).parse() var = TestIfParser([True, "and", True, "and", False]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser([False, 'or', False, 'or', False]).parse() var = TestIfParser([False, "or", False, "or", False]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser([False, 'or', True, 'and', False]).parse() var = TestIfParser([False, "or", True, "and", False]).parse()
assert not var.resolve({}) assert not var.resolve({})
var = TestIfParser([False, 'and', True, 'or', False]).parse() var = TestIfParser([False, "and", True, "or", False]).parse()
assert not var.resolve({}) assert not var.resolve({})
def test_invalid(): def test_invalid():
pytest.raises(ValueError, TestIfParser(['not']).parse) pytest.raises(ValueError, TestIfParser(["not"]).parse)
pytest.raises(ValueError, TestIfParser(['==']).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, '>', 'in']).parse) pytest.raises(ValueError, TestIfParser([1, ">", "in"]).parse)
pytest.raises(ValueError, TestIfParser([1, '==', 'not', 'not']).parse) pytest.raises(ValueError, TestIfParser([1, "==", "not", "not"]).parse)
pytest.raises(ValueError, TestIfParser([1, 2]).parse) pytest.raises(ValueError, TestIfParser([1, 2]).parse)

85
sigi/apps/diagnosticos/urls.py

@ -3,50 +3,71 @@ from django.conf.urls import patterns, url
from django.views.generic import TemplateView from django.views.generic import TemplateView
LOGIN_REDIRECT_URL = '/diagnosticos/mobile/login' LOGIN_REDIRECT_URL = "/diagnosticos/mobile/login"
urlpatterns = patterns( urlpatterns = patterns(
'sigi.apps.diagnosticos.views', "sigi.apps.diagnosticos.views",
# Lista de Diagnósticos # Lista de Diagnósticos
url(r'^mobile/$', 'lista', name='lista_diagnosticos'), url(r"^mobile/$", "lista", name="lista_diagnosticos"),
# Lista de Categorias # Lista de Categorias
url(r'^mobile/(?P<id_diagnostico>\d+)/categorias/$', url(
'categorias', name='lista_categorias'), r"^mobile/(?P<id_diagnostico>\d+)/categorias/$",
"categorias",
name="lista_categorias",
),
# Detalhes da Categoria da Casa Legislativa # Detalhes da Categoria da Casa Legislativa
url(r'^mobile/(?P<id_diagnostico>\d+)/categorias/1/$', url(
'categoria_casa_legislativa', name='detalhes_categoria_casa_legislativa'), r"^mobile/(?P<id_diagnostico>\d+)/categorias/1/$",
"categoria_casa_legislativa",
name="detalhes_categoria_casa_legislativa",
),
# Detalhes da Categoria de Contatos # Detalhes da Categoria de Contatos
url(r'^mobile/(?P<id_diagnostico>\d+)/categorias/2/$', url(
'categoria_contatos', name='detalhes_categoria_contatos'), r"^mobile/(?P<id_diagnostico>\d+)/categorias/2/$",
"categoria_contatos",
name="detalhes_categoria_contatos",
),
# Detalhes de Categorias Dinamicas # Detalhes de Categorias Dinamicas
url(r'^mobile/(?P<id_diagnostico>\d+)/categorias/(?P<id_categoria>\d+)/$', url(
'categoria_detalhes', name='detalhes_categoria'), r"^mobile/(?P<id_diagnostico>\d+)/categorias/(?P<id_categoria>\d+)/$",
"categoria_detalhes",
url(r'^mapa/$', TemplateView.as_view(template_name="diagnosticos/mapa.html"), name='template-mapa'), name="detalhes_categoria",
url(r'^mundiagjson/$', 'municipios_diagnosticados', name='municipios-diagnosticados'), ),
url(
r"^mapa/$",
TemplateView.as_view(template_name="diagnosticos/mapa.html"),
name="template-mapa",
),
url(
r"^mundiagjson/$",
"municipios_diagnosticados",
name="municipios-diagnosticados",
),
# Reports diagnosticos # Reports diagnosticos
url(r'^diagnostico/(?P<id_diagnostico>\w+).pdf$', 'diagnostico_pdf', name='diagnostico-pdf'), url(
r"^diagnostico/(?P<id_diagnostico>\w+).pdf$",
"diagnostico_pdf",
name="diagnostico-pdf",
),
# Graficos de perguntas # Graficos de perguntas
url(r'^graficos/$', 'graficos', name="diagnosticos-graficos"), # tagerror url(r"^graficos/$", "graficos", name="diagnosticos-graficos"), # tagerror
url(r'^api/$', 'grafico_api', name="diagnosticos-grafico-api"), # tagerror url(r"^api/$", "grafico_api", name="diagnosticos-grafico-api"), # tagerror
) )
urlpatterns += patterns( urlpatterns += patterns(
'django.contrib.auth.views', "django.contrib.auth.views",
# Login do Diagnóstico # Login do Diagnóstico
url(r'^mobile/login/$', 'login', {'template_name': url(
'diagnosticos/diagnosticos_login.html'}, name='login'), r"^mobile/login/$",
"login",
{"template_name": "diagnosticos/diagnosticos_login.html"},
name="login",
),
# Logout do Diagnóstico # Logout do Diagnóstico
url(r'^mobile/logout/$', 'logout', url(
{'next_page': LOGIN_REDIRECT_URL}, name='logout'), r"^mobile/logout/$",
"logout",
{"next_page": LOGIN_REDIRECT_URL},
name="logout",
),
) )

339
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.casas.models import Funcionario
from sigi.apps.contatos.models import Telefone from sigi.apps.contatos.models import Telefone
from sigi.apps.diagnosticos.decorators import validate_diagnostico from sigi.apps.diagnosticos.decorators import validate_diagnostico
from sigi.apps.diagnosticos.forms import (DiagnosticoMobileForm, from sigi.apps.diagnosticos.forms import (
OrgaoMobileForm, FuncionariosMobileForm) DiagnosticoMobileForm,
OrgaoMobileForm,
FuncionariosMobileForm,
)
from sigi.apps.diagnosticos.models import Diagnostico, Categoria, Pergunta from sigi.apps.diagnosticos.models import Diagnostico, Categoria, Pergunta
from sigi.apps.diagnosticos.urls import LOGIN_REDIRECT_URL from sigi.apps.diagnosticos.urls import LOGIN_REDIRECT_URL
from sigi.apps.utils.decorators import login_required from sigi.apps.utils.decorators import login_required
@ -27,8 +30,8 @@ def lista(request):
""" """
servidor = request.user.servidor servidor = request.user.servidor
diagnosticos = servidor.diagnosticos diagnosticos = servidor.diagnosticos
context = RequestContext(request, {'diagnosticos': diagnosticos}) context = RequestContext(request, {"diagnosticos": diagnosticos})
return render_to_response('diagnosticos/diagnosticos_list.html', context) return render_to_response("diagnosticos/diagnosticos_list.html", context)
@never_cache @never_cache
@ -44,12 +47,19 @@ def categorias(request, id_diagnostico):
# Estilizando a lista de categorias para que ajude a identificar # Estilizando a lista de categorias para que ajude a identificar
# qual categoria foi a ultima a ser usada, como também as outras # qual categoria foi a ultima a ser usada, como também as outras
# que ainda não foram acessadas # que ainda não foram acessadas
ultima_categoria = request.session.get('ultima_categoria', 0) ultima_categoria = request.session.get("ultima_categoria", 0)
context = RequestContext(request, {'categorias': categorias, context = RequestContext(
'diagnostico': diagnostico, 'ultima_categoria': ultima_categoria}) request,
return render_to_response('diagnosticos/diagnosticos_categorias_list.html', {
context) "categorias": categorias,
"diagnostico": diagnostico,
"ultima_categoria": ultima_categoria,
},
)
return render_to_response(
"diagnosticos/diagnosticos_categorias_list.html", context
)
@never_cache @never_cache
@ -68,40 +78,42 @@ def categoria_detalhes(request, id_diagnostico, id_categoria):
# Grava na sessão a categoria atual, para destacar que # Grava na sessão a categoria atual, para destacar que
# era foi a última visitada. # era foi a última visitada.
request.session['ultima_categoria'] = int(id_categoria) request.session["ultima_categoria"] = int(id_categoria)
try: try:
categoria = Categoria.objects.get(pk=id_categoria) categoria = Categoria.objects.get(pk=id_categoria)
except Categoria.DoesNotExist: except Categoria.DoesNotExist:
context = RequestContext(request) 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": if request.method == "POST":
form = DiagnosticoMobileForm(request.POST, form = DiagnosticoMobileForm(
instance=diagnostico, category=id_categoria) request.POST, instance=diagnostico, category=id_categoria
)
if form.is_valid(): if form.is_valid():
form.save() form.save()
resposta = { resposta = {"mensagem": "sucesso"}
'mensagem': 'sucesso'
}
else: else:
# Montando a estrutura das mensagens de erro no formato JSON # Montando a estrutura das mensagens de erro no formato JSON
resposta = { resposta = {"mensagem": "erro", "erros": form.errors}
'mensagem': 'erro',
'erros': form.errors
}
json = simplejson.dumps(resposta) json = simplejson.dumps(resposta)
return HttpResponse(json, content_type='application/json') return HttpResponse(json, content_type="application/json")
else: else:
form = DiagnosticoMobileForm(instance=diagnostico, form = DiagnosticoMobileForm(
category=id_categoria) instance=diagnostico, category=id_categoria
)
context = RequestContext(request, {'form': form, 'categoria': categoria,
'diagnostico': diagnostico}) context = RequestContext(
return render_to_response('diagnosticos/diagnosticos_categorias_form.html', request,
context) {"form": form, "categoria": categoria, "diagnostico": diagnostico},
)
return render_to_response(
"diagnosticos/diagnosticos_categorias_form.html", context
)
@never_cache @never_cache
@ -111,35 +123,36 @@ def categoria_casa_legislativa(request, id_diagnostico):
# Grava na sessão a categoria atual, para destacar que # Grava na sessão a categoria atual, para destacar que
# era foi a última visitada. # era foi a última visitada.
request.session['ultima_categoria'] = 1 request.session["ultima_categoria"] = 1
diagnostico = Diagnostico.objects.get(pk=id_diagnostico) diagnostico = Diagnostico.objects.get(pk=id_diagnostico)
casa_legislativa = diagnostico.casa_legislativa casa_legislativa = diagnostico.casa_legislativa
if request.method == "POST": if request.method == "POST":
form = OrgaoMobileForm(request.POST, form = OrgaoMobileForm(request.POST, instance=casa_legislativa)
instance=casa_legislativa)
if form.is_valid(): if form.is_valid():
form.save() form.save()
resposta = { resposta = {"mensagem": "sucesso"}
'mensagem': 'sucesso'
}
else: else:
# Montando a estrutura das mensagens de erro no formato JSON # Montando a estrutura das mensagens de erro no formato JSON
resposta = { resposta = {"mensagem": "erro", "erros": form.errors}
'mensagem': 'erro',
'erros': form.errors
}
json = simplejson.dumps(resposta) json = simplejson.dumps(resposta)
return HttpResponse(json, content_type='application/json') return HttpResponse(json, content_type="application/json")
else: else:
form = OrgaoMobileForm(instance=casa_legislativa) form = OrgaoMobileForm(instance=casa_legislativa)
context = RequestContext(request, {'form': form, context = RequestContext(
'diagnostico': diagnostico, 'casa_legislativa': casa_legislativa}) request,
{
"form": form,
"diagnostico": diagnostico,
"casa_legislativa": casa_legislativa,
},
)
return render_to_response( return render_to_response(
'diagnosticos/diagnosticos_categoria_casa_legislativa_form.html', "diagnosticos/diagnosticos_categoria_casa_legislativa_form.html",
context) context,
)
@never_cache @never_cache
@ -149,7 +162,7 @@ def categoria_contatos(request, id_diagnostico):
# Grava na sessão a categoria atual, para destacar que # Grava na sessão a categoria atual, para destacar que
# era foi a última visitada. # era foi a última visitada.
request.session['ultima_categoria'] = 2 request.session["ultima_categoria"] = 2
diagnostico = Diagnostico.objects.get(pk=id_diagnostico) diagnostico = Diagnostico.objects.get(pk=id_diagnostico)
casa_legislativa = diagnostico.casa_legislativa casa_legislativa = diagnostico.casa_legislativa
@ -158,7 +171,9 @@ def categoria_contatos(request, id_diagnostico):
for n, l in Funcionario.SETOR_CHOICES: for n, l in Funcionario.SETOR_CHOICES:
if casa_legislativa.funcionario_set.filter(setor=n).count() <= 1: 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: else:
for f in casa_legislativa.funcionario_set.filter(setor=n): for f in casa_legislativa.funcionario_set.filter(setor=n):
funcionarios.append((f, False)) funcionarios.append((f, False))
@ -167,64 +182,94 @@ def categoria_contatos(request, id_diagnostico):
forms = [] forms = []
for f, c in funcionarios: for f, c in funcionarios:
try: try:
forms.append(FuncionariosMobileForm(request.POST, prefix=f.setor, instance=f)) forms.append(
FuncionariosMobileForm(
request.POST, prefix=f.setor, instance=f
)
)
except: except:
pass pass
resposta = { resposta = {
'mensagem': 'sucesso', "mensagem": "sucesso",
'erros': {}, "erros": {},
'fones': {}, "fones": {},
'clean': (), "clean": (),
} }
# valida e salva um formulario por vez # valida e salva um formulario por vez
for form in forms: for form in forms:
if form.is_valid(): if form.is_valid():
form.save() form.save()
s = '' s = ""
for form_telefones in form.telefones.forms: for form_telefones in form.telefones.forms:
tel = form_telefones.instance tel = form_telefones.instance
if tel._state.adding and tel.numero != '': if tel._state.adding and tel.numero != "":
s += _('<p>Novo telefone %(type)s: %(number)s</p>') % dict( s += _(
"<p>Novo telefone %(type)s: %(number)s</p>"
) % dict(
type=form_telefones.instance.get_tipo_display(), type=form_telefones.instance.get_tipo_display(),
number=form_telefones.instance.numero) number=form_telefones.instance.numero,
resposta['clean'] += ('id_' + form_telefones.prefix + '-numero',) )
if s != '': resposta["clean"] += (
resposta['fones'][form.prefix] = s "id_" + form_telefones.prefix + "-numero",
)
if s != "":
resposta["fones"][form.prefix] = s
else: else:
# Montando a estrutura das mensagens de erro no formato JSON # Montando a estrutura das mensagens de erro no formato JSON
resposta['mensagem'] = 'erro' resposta["mensagem"] = "erro"
for key, value in form.errors.iteritems(): 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: for form_telefones in form.telefones.forms:
if not form_telefones.is_valid(): if not form_telefones.is_valid():
if (form_telefones.fields['id'].initial is not None if (
and form_telefones.fields['tipo'].initial == 'I' form_telefones.fields["id"].initial is not None
and form_telefones.fields['numero'].initial is None): and form_telefones.fields["tipo"].initial == "I"
if Telefone.objects.filter(pk=form_telefones.fields['id'].initial).exists(): and form_telefones.fields["numero"].initial is None
Telefone.objects.get(pk=form_telefones.fields['id'].initial).delete() ):
if form.prefix not in resposta['fones']: if Telefone.objects.filter(
resposta['fones'][form.prefix] = '' pk=form_telefones.fields["id"].initial
resposta['fones'][form.prefix] += _('<p>O telefone %(type)s %(number)s foi excluído da base de dados</p>') % dict( ).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] += _(
"<p>O telefone %(type)s %(number)s foi excluído da base de dados</p>"
) % dict(
type=form_telefones.instance.get_tipo_display(), type=form_telefones.instance.get_tipo_display(),
number=form_telefones.instance.numero) number=form_telefones.instance.numero,
)
else: else:
for key, value in form_telefones.errors.iteritems(): for key, value in form_telefones.errors.iteritems():
key = form_telefones.prefix + "-id-errors" key = form_telefones.prefix + "-id-errors"
resposta['erros'][key] = value resposta["erros"][key] = value
json = simplejson.dumps(resposta) json = simplejson.dumps(resposta)
return HttpResponse(json, content_type='application/json') return HttpResponse(json, content_type="application/json")
else: else:
forms = [FuncionariosMobileForm(prefix=f.setor, instance=f) forms = [
for f, c in funcionarios] 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 @login_required
def diagnostico_pdf(request, id_diagnostico): def diagnostico_pdf(request, id_diagnostico):
@ -235,7 +280,9 @@ def diagnostico_pdf(request, id_diagnostico):
funcionarios = [] funcionarios = []
for n, l in Funcionario.SETOR_CHOICES: for n, l in Funcionario.SETOR_CHOICES:
if casa_legislativa.funcionario_set.filter(setor=n).count() <= 1: 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: else:
for f in casa_legislativa.funcionario_set.filter(setor=n): for f in casa_legislativa.funcionario_set.filter(setor=n):
funcionarios.append(f) funcionarios.append(f)
@ -249,24 +296,28 @@ def diagnostico_pdf(request, id_diagnostico):
if datatype == schema.TYPE_MANY: if datatype == schema.TYPE_MANY:
schema.value = [x.pk for x in data] schema.value = [x.pk for x in data]
elif datatype == schema.TYPE_ONE: elif datatype == schema.TYPE_ONE:
schema.value = data.pk if data else None, schema.value = (data.pk if data else None,)
else: else:
schema.value = data schema.value = data
schemas.append(schema) schemas.append(schema)
schemas_by_categoria.append((categoria, schemas)) schemas_by_categoria.append((categoria, schemas))
context = RequestContext(request, { context = RequestContext(
'pagesize': 'A4', request,
'casa_legislativa': casa_legislativa, {
'funcionarios': funcionarios, "pagesize": "A4",
'diagnostico': diagnostico, "casa_legislativa": casa_legislativa,
'schemas_by_categoria': schemas_by_categoria, "funcionarios": funcionarios,
}) "diagnostico": diagnostico,
"schemas_by_categoria": schemas_by_categoria,
return render_to_pdf('diagnosticos/diagnostico_pdf.html', context) },
)
return render_to_pdf("diagnosticos/diagnostico_pdf.html", context)
# return render_to_response('diagnosticos/diagnostico_pdf.html', context) # return render_to_response('diagnosticos/diagnostico_pdf.html', context)
@login_required @login_required
def graficos(request): def graficos(request):
categorias = Categoria.objects.all() categorias = Categoria.objects.all()
@ -274,73 +325,101 @@ def graficos(request):
sel_categoria = int(request.REQUEST.get("categoria", "3")) sel_categoria = int(request.REQUEST.get("categoria", "3"))
perguntas = Pergunta.objects.filter(categoria=sel_categoria).all() perguntas = Pergunta.objects.filter(categoria=sel_categoria).all()
context = RequestContext(request, { context = RequestContext(
'categorias': categorias, request,
'sel_categoria': sel_categoria, {
'perguntas': perguntas, "categorias": categorias,
}) "sel_categoria": sel_categoria,
return render_to_response('diagnosticos/graficos.html', "perguntas": perguntas,
context) },
)
return render_to_response("diagnosticos/graficos.html", context)
def percentage(fraction, population): def percentage(fraction, population):
try: try:
return "%.0f%%" % ((float(fraction) / float(population)) * 100) return "%.0f%%" % ((float(fraction) / float(population)) * 100)
except ValueError: except ValueError:
return '' return ""
@login_required @login_required
def grafico_api(request): def grafico_api(request):
colors = cycle(['#7cb5ec', colors = cycle(
'#434348', [
'#90ed7d', "#7cb5ec",
'#f7a35c', "#434348",
'#8085e9', "#90ed7d",
'#f15c80', "#f7a35c",
'#e4d354', "#8085e9",
'#8085e8', "#f15c80",
'#8d4653', "#e4d354",
'#91e8e1', ]) "#8085e8",
"#8d4653",
highlights = cycle(['#B0D3F4', "#91e8e1",
'#8E8E91', ]
'#BCF4B1', )
'#FAC89D',
'#B3B6F2', highlights = cycle(
'#F79DB3', [
'#EFE598', "#B0D3F4",
'#B3B6F1', "#8E8E91",
'#BB9098', "#BCF4B1",
'#BDF1ED', ]) "#FAC89D",
"#B3B6F2",
pergunta_slug = request.REQUEST.get('id', None) "#F79DB3",
"#EFE598",
"#B3B6F1",
"#BB9098",
"#BDF1ED",
]
)
pergunta_slug = request.REQUEST.get("id", None)
pergunta = get_object_or_404(Pergunta, name=pergunta_slug) pergunta = get_object_or_404(Pergunta, name=pergunta_slug)
if pergunta.datatype == 'one': if pergunta.datatype == "one":
list_perguntas = pergunta.group_choices() list_perguntas = pergunta.group_choices()
list_perguntas = [{'label': k.title, list_perguntas = [
'value': v, {
'color': colors.next(), "label": k.title,
'highlight': highlights.next()} "value": v,
for k, v in list_perguntas] "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] # list_perguntas = [[k.title, v, colors.next(), highlights.next()] for k, v in list_perguntas]
# elif pergunta.datatype == 'many': # 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") return HttpResponse(jsonn, content_type="application/json")
@login_required @login_required
def municipios_diagnosticados(self): def municipios_diagnosticados(self):
municipios = [] municipios = []
for d in Diagnostico.objects.all(): for d in Diagnostico.objects.all():
m = d.casa_legislativa.municipio 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, municipio = {
'fim': d.data_visita_fim, 'equipe': "<ul><li>" + "</li><li>".join([m.user.get_full_name() for m in d.membros]) + "</li></ul>", } "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": "<ul><li>"
+ "</li><li>".join([m.user.get_full_name() for m in d.membros])
+ "</li></ul>",
}
municipios.append(municipio) municipios.append(municipio)
return HttpResponse(simplejson.dumps(municipios), content_type='application/json') return HttpResponse(
simplejson.dumps(municipios), content_type="application/json"
)

43
sigi/apps/diagnosticos/widgets.py

@ -1,5 +1,11 @@
from itertools import chain 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.html import conditional_escape
from django.utils.encoding import force_unicode from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
@ -7,34 +13,39 @@ from sigi.apps.diagnosticos.models import Escolha
class EavCheckboxSelectMultiple(CheckboxSelectMultiple): class EavCheckboxSelectMultiple(CheckboxSelectMultiple):
def render(self, name, value, attrs=None, choices=()): def render(self, name, value, attrs=None, choices=()):
if value is None: if value is None:
value = [] value = []
final_attrs = self.build_attrs(attrs, name=name) final_attrs = self.build_attrs(attrs, name=name)
output = ['<ul>'] output = ["<ul>"]
str_values = set([force_unicode(v) for v in value]) str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): for i, (option_value, option_label) in enumerate(
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) chain(self.choices, choices)
label_for = ' for="%s"' % final_attrs['id'] ):
final_attrs = dict(final_attrs, id="%s_%s" % (attrs["id"], i))
label_for = ' for="%s"' % final_attrs["id"]
# Caso exista uma pergunta para abrir # Caso exista uma pergunta para abrir
# adiciona um atripbuto no checkbox # adiciona um atripbuto no checkbox
schema_to_open = Escolha.objects.get(pk=option_value).schema_to_open schema_to_open = Escolha.objects.get(pk=option_value).schema_to_open
if 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) option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value) rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label)) option_label = conditional_escape(force_unicode(option_label))
output.append('<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label)) output.append(
output.append('</ul>') "<li><label%s>%s %s</label></li>"
return mark_safe('\n'.join(output)) % (label_for, rendered_cb, option_label)
)
output.append("</ul>")
return mark_safe("\n".join(output))
class EavRadioFieldRenderer(RadioFieldRenderer): class EavRadioFieldRenderer(RadioFieldRenderer):
def __iter__(self): def __iter__(self):
for i, choice in enumerate(self.choices): for i, choice in enumerate(self.choices):
final_attrs = self.attrs.copy() final_attrs = self.attrs.copy()
@ -42,9 +53,11 @@ class EavRadioFieldRenderer(RadioFieldRenderer):
# Caso exista uma pergunta para abrir # Caso exista uma pergunta para abrir
# adiciona um atripbuto no checkbox # adiciona um atripbuto no checkbox
if choice[0]: 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: 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) yield RadioInput(self.name, self.value, final_attrs, choice, i)
@ -57,7 +70,7 @@ class EavRadioFieldRenderer(RadioFieldRenderer):
# adiciona um atripbuto no checkbox # adiciona um atripbuto no checkbox
schema_to_open = Escolha.objects.get(pk=self.value).schema_to_open schema_to_open = Escolha.objects.get(pk=self.value).schema_to_open
if 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) return RadioInput(self.name, self.value, final_attrs, choice, idx)

161
sigi/apps/eventos/admin.py

@ -4,94 +4,163 @@ from django.utils.translation import gettext as _
from import_export.fields import Field from import_export.fields import Field
from tinymce.models import HTMLField from tinymce.models import HTMLField
from tinymce.widgets import AdminTinyMCE from tinymce.widgets import AdminTinyMCE
from sigi.apps.eventos.models import (ModeloDeclaracao, Modulo, TipoEvento, from sigi.apps.eventos.models import (
Funcao, Evento, Equipe, Convite, Anexo) ModeloDeclaracao,
Modulo,
TipoEvento,
Funcao,
Evento,
Equipe,
Convite,
Anexo,
)
from sigi.apps.eventos.forms import EventoAdminForm from sigi.apps.eventos.forms import EventoAdminForm
from sigi.apps.utils.filters import EmptyFilter from sigi.apps.utils.filters import EmptyFilter
from sigi.apps.utils.mixins import CartExportMixin, ValueLabeledResource from sigi.apps.utils.mixins import CartExportMixin, ValueLabeledResource
class EventoResource(ValueLabeledResource): class EventoResource(ValueLabeledResource):
# categoria_evento = Field(column_name="tipo_evento__categoria") # categoria_evento = Field(column_name="tipo_evento__categoria")
# status = Field(column_name="status") # status = Field(column_name="status")
class Meta: class Meta:
model = Evento model = Evento
fields = ( fields = (
'id', 'tipo_evento__nome', 'tipo_evento__categoria', 'nome', "id",
'descricao', 'virtual', 'solicitante', 'num_processo', "tipo_evento__nome",
'data_pedido', 'data_inicio', 'data_termino', 'carga_horaria', "tipo_evento__categoria",
'casa_anfitria__nome', 'casa_anfitria__logradouro', "nome",
'casa_anfitria__bairro', 'casa_anfitria__municipio__nome', "descricao",
'casa_anfitria__municipio__uf__sigla', 'casa_anfitria__cep', "virtual",
'casa_anfitria__email', 'local', 'municipio__nome', "solicitante",
'municipio__uf__sigla', 'observacao', 'publico_alvo', "num_processo",
'total_participantes', 'status', 'data_cancelamento', "data_pedido",
'motivo_cancelamento', 'equipe__membro__nome_completo', "data_inicio",
'equipe__funcao__nome', 'convite__casa__nome', "data_termino",
'convite__casa__municipio__nome', "carga_horaria",
'convite__casa__municipio__uf__sigla', 'convite__casa__cep', "casa_anfitria__nome",
'convite__casa__email', 'convite__aceite', 'convite__data_convite', "casa_anfitria__logradouro",
'convite__participou', 'convite__qtde_participantes', "casa_anfitria__bairro",
'convite__nomes_participantes', "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 export_order = fields
def dehydrate_tipo_evento__categoria(self, obj): 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): 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): 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): 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): 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) @admin.register(TipoEvento)
class TipoEventAdmin(admin.ModelAdmin): class TipoEventAdmin(admin.ModelAdmin):
search_fields = ('nome',) search_fields = ("nome",)
@admin.register(Funcao) @admin.register(Funcao)
class FuncaoAdmin(admin.ModelAdmin): class FuncaoAdmin(admin.ModelAdmin):
list_display = ('nome', 'descricao',) list_display = (
search_fields = ('nome', 'descricao',) "nome",
"descricao",
)
search_fields = (
"nome",
"descricao",
)
@admin.register(ModeloDeclaracao) @admin.register(ModeloDeclaracao)
class ModeloDeclaracaoAdmin(admin.ModelAdmin): class ModeloDeclaracaoAdmin(admin.ModelAdmin):
list_display = ('nome', 'formato') list_display = ("nome", "formato")
formfield_overrides = {HTMLField: {'widget': AdminTinyMCE}} formfield_overrides = {HTMLField: {"widget": AdminTinyMCE}}
class EquipeInline(admin.StackedInline): class EquipeInline(admin.StackedInline):
model = Equipe model = Equipe
class ConviteInline(admin.StackedInline): class ConviteInline(admin.StackedInline):
model = Convite model = Convite
raw_id_fields = ('casa',) raw_id_fields = ("casa",)
class ModuloInline(admin.StackedInline): class ModuloInline(admin.StackedInline):
model = Modulo model = Modulo
class AnexoInline(admin.StackedInline): class AnexoInline(admin.StackedInline):
model = Anexo model = Anexo
exclude = ('data_pub',) exclude = ("data_pub",)
@admin.register(Evento) @admin.register(Evento)
class EventoAdmin(CartExportMixin, admin.ModelAdmin): class EventoAdmin(CartExportMixin, admin.ModelAdmin):
form = EventoAdminForm form = EventoAdminForm
resource_class = EventoResource resource_class = EventoResource
date_hierarchy = 'data_inicio' date_hierarchy = "data_inicio"
list_display = ('nome', 'tipo_evento', 'status', 'link_sigad', list_display = (
'data_inicio', 'data_termino', 'municipio', 'solicitante', "nome",
'total_participantes',) "tipo_evento",
list_filter = ('status', ('num_processo', EmptyFilter), 'tipo_evento', "status",
'tipo_evento__categoria', 'virtual', 'municipio__uf', "link_sigad",
'solicitante') "data_inicio",
raw_id_fields = ('casa_anfitria', 'municipio',) "data_termino",
search_fields = ('nome', 'tipo_evento__nome', 'casa_anfitria__search_text', "municipio",
'municipio__search_text', 'solicitante') "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) inlines = (EquipeInline, ConviteInline, ModuloInline, AnexoInline)
save_as = True save_as = True
@ -99,10 +168,14 @@ class EventoAdmin(CartExportMixin, admin.ModelAdmin):
if obj.pk is None: if obj.pk is None:
return "" return ""
return obj.get_sigad_url() 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 link_sigad.allow_tags = True
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return (super(EventoAdmin, self).lookup_allowed(lookup, value) or return super(EventoAdmin, self).lookup_allowed(
lookup in ['tipo_evento__nome__exact', lookup, value
'tipo_evento__nome__contains']) ) or lookup in [
"tipo_evento__nome__exact",
"tipo_evento__nome__contains",
]

5
sigi/apps/eventos/apps.py

@ -1,6 +1,7 @@
from django.apps import AppConfig from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class EventosConfig(AppConfig): class EventosConfig(AppConfig):
name = 'sigi.apps.eventos' name = "sigi.apps.eventos"
verbose_name = _('Eventos Interlegis') verbose_name = _("Eventos Interlegis")

30
sigi/apps/eventos/forms.py

@ -2,14 +2,31 @@ from django import forms
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from sigi.apps.eventos.models import ModeloDeclaracao, Evento from sigi.apps.eventos.models import ModeloDeclaracao, Evento
class EventoAdminForm(forms.ModelForm): class EventoAdminForm(forms.ModelForm):
class Meta: class Meta:
model = Evento model = Evento
fields = ('tipo_evento', 'nome', 'descricao', 'virtual', 'solicitante', fields = (
'num_processo', 'data_pedido', 'data_inicio', 'data_termino', "tipo_evento",
'carga_horaria', 'casa_anfitria', 'municipio', 'observacao', "nome",
'local', 'publico_alvo', 'total_participantes', 'status', "descricao",
'data_cancelamento', 'motivo_cancelamento', ) "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): def clean(self):
cleaned_data = super(EventoAdminForm, self).clean() cleaned_data = super(EventoAdminForm, self).clean()
@ -19,9 +36,10 @@ class EventoAdminForm(forms.ModelForm):
if data_inicio > data_termino: if data_inicio > data_termino:
raise forms.ValidationError( raise forms.ValidationError(
_("Data término deve ser posterior à data inicio"), _("Data término deve ser posterior à data inicio"),
code="invalid_period" code="invalid_period",
) )
class SelecionaModeloForm(forms.Form): class SelecionaModeloForm(forms.Form):
modelo = forms.ModelChoiceField( modelo = forms.ModelChoiceField(
queryset=ModeloDeclaracao.objects.all(), queryset=ModeloDeclaracao.objects.all(),

298
sigi/apps/eventos/migrations/0001_initial.py

@ -7,130 +7,292 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0001_initial'), ("servidores", "0001_initial"),
('contatos', '0001_initial'), ("contatos", "0001_initial"),
('casas', '0002_auto_20150710_1247'), ("casas", "0002_auto_20150710_1247"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Convite', name="Convite",
fields=[ fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), (
('data_convite', models.DateField(verbose_name='Data do convite')), "id",
('aceite', models.BooleanField(default=False, verbose_name='Aceitou o convite')), models.AutoField(
('participou', models.BooleanField(default=False, verbose_name='Participou do evento')), verbose_name="ID",
('casa', models.ForeignKey(verbose_name='Casa convidada', to='casas.CasaLegislativa', on_delete=models.CASCADE)), 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={ options={
'ordering': ('evento', 'casa', '-data_convite'), "ordering": ("evento", "casa", "-data_convite"),
'verbose_name': 'Casa convidada', "verbose_name": "Casa convidada",
'verbose_name_plural': 'Casas convidadas', "verbose_name_plural": "Casas convidadas",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Equipe', name="Equipe",
fields=[ 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={ options={
'ordering': ('evento', 'funcao', 'membro'), "ordering": ("evento", "funcao", "membro"),
'verbose_name': 'Membro da equipe', "verbose_name": "Membro da equipe",
'verbose_name_plural': 'Membros da equipe', "verbose_name_plural": "Membros da equipe",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Evento', name="Evento",
fields=[ 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')), "id",
('descricao', models.TextField(verbose_name='Descri\xe7\xe3o do evento')), models.AutoField(
('solicitante', models.CharField(max_length=100, verbose_name='Solicitante')), verbose_name="ID",
('data_inicio', models.DateField(verbose_name='Data de in\xedcio')), serialize=False,
('data_termino', models.DateField(verbose_name='Data de t\xe9rmino')), auto_created=True,
('local', models.TextField(verbose_name='Local do evento', blank=True)), primary_key=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)), "nome",
('casa_anfitria', models.ForeignKey(verbose_name='Casa anfitri\xe3', blank=True, to='casas.CasaLegislativa', null=True, on_delete=models.CASCADE)), models.CharField(
('municipio', models.ForeignKey(to='contatos.Municipio', on_delete=models.CASCADE)), 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={ options={
'ordering': ('-data_inicio',), "ordering": ("-data_inicio",),
'verbose_name': 'Evento', "verbose_name": "Evento",
'verbose_name_plural': 'Eventos', "verbose_name_plural": "Eventos",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='Funcao', name="Funcao",
fields=[ 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')), "id",
('descricao', models.TextField(verbose_name='Descri\xe7\xe3o da fun\xe7\xe3o')), 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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'Fun\xe7\xe3o', "verbose_name": "Fun\xe7\xe3o",
'verbose_name_plural': 'Fun\xe7\xf5es', "verbose_name_plural": "Fun\xe7\xf5es",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.CreateModel( migrations.CreateModel(
name='TipoEvento', name="TipoEvento",
fields=[ 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={ options={
'ordering': ('nome',), "ordering": ("nome",),
'verbose_name': 'Tipo de evento', "verbose_name": "Tipo de evento",
'verbose_name_plural': 'Tipos de evento', "verbose_name_plural": "Tipos de evento",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),
migrations.AddField( migrations.AddField(
model_name='evento', model_name="evento",
name='tipo_evento', name="tipo_evento",
field=models.ForeignKey(to='eventos.TipoEvento', on_delete=models.CASCADE), field=models.ForeignKey(
to="eventos.TipoEvento", on_delete=models.CASCADE
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='equipe', model_name="equipe",
name='evento', name="evento",
field=models.ForeignKey(to='eventos.Evento', on_delete=models.CASCADE), field=models.ForeignKey(
to="eventos.Evento", on_delete=models.CASCADE
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='equipe', model_name="equipe",
name='funcao', name="funcao",
field=models.ForeignKey(verbose_name='Fun\xe7\xe3o na equipe', to='eventos.Funcao', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Fun\xe7\xe3o na equipe",
to="eventos.Funcao",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='equipe', model_name="equipe",
name='membro', name="membro",
field=models.ForeignKey(related_name='equipe_evento', to='servidores.Servidor', on_delete=models.CASCADE), field=models.ForeignKey(
related_name="equipe_evento",
to="servidores.Servidor",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convite', model_name="convite",
name='evento', name="evento",
field=models.ForeignKey(to='eventos.Evento', on_delete=models.CASCADE), field=models.ForeignKey(
to="eventos.Evento", on_delete=models.CASCADE
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convite', model_name="convite",
name='servidor', name="servidor",
field=models.ForeignKey(verbose_name='Servidor que convido', to='servidores.Servidor', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Servidor que convido",
to="servidores.Servidor",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterUniqueTogether( migrations.AlterUniqueTogether(
name='convite', name="convite",
unique_together=set([('evento', 'casa')]), unique_together=set([("evento", "casa")]),
), ),
] ]

5
sigi/apps/eventos/migrations/0002_auto_20151016_1449.py

@ -7,8 +7,7 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0001_initial'), ("eventos", "0001_initial"),
] ]
operations = [ operations = []
]

5
sigi/apps/eventos/migrations/0003_auto_20151104_0810.py

@ -7,8 +7,7 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0002_auto_20151016_1449'), ("eventos", "0002_auto_20151016_1449"),
] ]
operations = [ operations = []
]

5
sigi/apps/eventos/migrations/0004_auto_20160719_0920.py

@ -7,8 +7,7 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0003_auto_20151104_0810'), ("eventos", "0003_auto_20151104_0810"),
] ]
operations = [ operations = []
]

5
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): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0003_auto_20151104_0810'), ("eventos", "0003_auto_20151104_0810"),
] ]
operations = [ operations = []
]

26
sigi/apps/eventos/migrations/0005_auto_20210406_1945.py

@ -7,21 +7,31 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0004_remove_evento_curso_moodle_id'), ("eventos", "0004_remove_evento_curso_moodle_id"),
('casas', '0014_auto_20210406_1945'), ("casas", "0014_auto_20210406_1945"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='convite', model_name="convite",
name='casa', name="casa",
field=models.ForeignKey(verbose_name='Casa convidada', to='casas.Orgao', on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Casa convidada",
to="casas.Orgao",
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='evento', model_name="evento",
name='casa_anfitria', name="casa_anfitria",
field=models.ForeignKey(verbose_name='Casa anfitri\xe3', blank=True, to='casas.Orgao', null=True, on_delete=models.CASCADE), field=models.ForeignKey(
verbose_name="Casa anfitri\xe3",
blank=True,
to="casas.Orgao",
null=True,
on_delete=models.CASCADE,
),
preserve_default=True, preserve_default=True,
), ),
] ]

72
sigi/apps/eventos/migrations/0006_auto_20210416_0841.py

@ -8,50 +8,78 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0005_auto_20210406_1945'), ("eventos", "0005_auto_20210406_1945"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='convite', model_name="convite",
name='casa', name="casa",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Casa convidada', to='casas.Orgao'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Casa convidada",
to="casas.Orgao",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='convite', model_name="convite",
name='servidor', name="servidor",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Servidor que convido', to='servidores.Servidor'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Servidor que convido",
to="servidores.Servidor",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='equipe', model_name="equipe",
name='funcao', name="funcao",
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Fun\xe7\xe3o na equipe', to='eventos.Funcao'), field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
verbose_name="Fun\xe7\xe3o na equipe",
to="eventos.Funcao",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='equipe', model_name="equipe",
name='membro', name="membro",
field=models.ForeignKey(related_name='equipe_evento', on_delete=django.db.models.deletion.PROTECT, to='servidores.Servidor'), field=models.ForeignKey(
related_name="equipe_evento",
on_delete=django.db.models.deletion.PROTECT,
to="servidores.Servidor",
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='evento', model_name="evento",
name='casa_anfitria', 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), 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, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='evento', model_name="evento",
name='municipio', name="municipio",
field=models.ForeignKey(to='contatos.Municipio', on_delete=django.db.models.deletion.PROTECT), field=models.ForeignKey(
to="contatos.Municipio",
on_delete=django.db.models.deletion.PROTECT,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='evento', model_name="evento",
name='tipo_evento', name="tipo_evento",
field=models.ForeignKey(to='eventos.TipoEvento', on_delete=django.db.models.deletion.PROTECT), field=models.ForeignKey(
to="eventos.TipoEvento",
on_delete=django.db.models.deletion.PROTECT,
),
preserve_default=True, preserve_default=True,
), ),
] ]

34
sigi/apps/eventos/migrations/0007_auto_20210417_0744.py

@ -7,32 +7,40 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0006_auto_20210416_0841'), ("eventos", "0006_auto_20210416_0841"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='convite', model_name="convite",
name='nomes_participantes', name="nomes_participantes",
field=models.TextField(help_text='Favor colocar um participante por linha', verbose_name='nome dos participantes', blank=True), field=models.TextField(
help_text="Favor colocar um participante por linha",
verbose_name="nome dos participantes",
blank=True,
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='convite', model_name="convite",
name='qtde_participantes', name="qtde_participantes",
field=models.PositiveIntegerField(default=0, verbose_name='n\xfamero de participantes'), field=models.PositiveIntegerField(
default=0, verbose_name="n\xfamero de participantes"
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='evento', model_name="evento",
name='carga_horaria', name="carga_horaria",
field=models.PositiveIntegerField(default=0, verbose_name='carga hor\xe1ria'), field=models.PositiveIntegerField(
default=0, verbose_name="carga hor\xe1ria"
),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='evento', model_name="evento",
name='virtual', name="virtual",
field=models.BooleanField(default=False, verbose_name='Virtual'), field=models.BooleanField(default=False, verbose_name="Virtual"),
preserve_default=True, preserve_default=True,
), ),
] ]

18
sigi/apps/eventos/migrations/0008_auto_20211104_1253.py

@ -7,20 +7,24 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0007_auto_20210417_0744'), ("eventos", "0007_auto_20210417_0744"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='evento', model_name="evento",
name='data_inicio', name="data_inicio",
field=models.DateTimeField(null=True, verbose_name='Data/hora do In\xedcio', blank=True), field=models.DateTimeField(
null=True, verbose_name="Data/hora do In\xedcio", blank=True
),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='evento', model_name="evento",
name='data_termino', name="data_termino",
field=models.DateTimeField(null=True, verbose_name='Data/hora do Termino', blank=True), field=models.DateTimeField(
null=True, verbose_name="Data/hora do Termino", blank=True
),
preserve_default=True, preserve_default=True,
), ),
] ]

19
sigi/apps/eventos/migrations/0009_tipoevento_categoria.py

@ -7,14 +7,25 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0008_auto_20211104_1253'), ("eventos", "0008_auto_20211104_1253"),
] ]
operations = [ operations = [
migrations.AddField( migrations.AddField(
model_name='tipoevento', model_name="tipoevento",
name='categoria', 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')]), 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, preserve_default=False,
), ),
] ]

110
sigi/apps/eventos/migrations/0010_modulo.py

@ -8,29 +8,107 @@ import django.db.models.deletion
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('servidores', '0007_auto_20210430_0735'), ("servidores", "0007_auto_20210430_0735"),
('eventos', '0009_tipoevento_categoria'), ("eventos", "0009_tipoevento_categoria"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Modulo', name="Modulo",
fields=[ 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",
('descricao', models.TextField(verbose_name='Descri\xe7\xe3o do m\xf3dulo')), models.AutoField(
('tipo', models.CharField(max_length=1, verbose_name='Tipo', choices=[('A', 'Aula'), ('P', 'Palestra'), ('R', 'Apresenta\xe7\xe3o')])), verbose_name="ID",
('inicio', models.DateTimeField(null=True, verbose_name='Data/hora de in\xedcio', blank=True)), serialize=False,
('termino', models.DateTimeField(null=True, verbose_name='Data/hora de t\xe9rmino', blank=True)), auto_created=True,
('carga_horaria', models.PositiveIntegerField(default=0, verbose_name='carga hor\xe1ria')), primary_key=True,
('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)), ("nome", models.CharField(max_length=100, verbose_name="Nome")),
('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')), (
"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={ options={
'verbose_name': 'M\xf3dulo do evento', "verbose_name": "M\xf3dulo do evento",
'verbose_name_plural': 'M\xf3dulos do evento', "verbose_name_plural": "M\xf3dulos do evento",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),

20
sigi/apps/eventos/migrations/0011_auto_20211117_0633.py

@ -7,18 +7,26 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0010_modulo'), ("eventos", "0010_modulo"),
] ]
operations = [ operations = [
migrations.AlterModelOptions( migrations.AlterModelOptions(
name='modulo', name="modulo",
options={'ordering': ('inicio',), 'verbose_name': 'M\xf3dulo do evento', 'verbose_name_plural': 'M\xf3dulos do evento'}, options={
"ordering": ("inicio",),
"verbose_name": "M\xf3dulo do evento",
"verbose_name_plural": "M\xf3dulos do evento",
},
), ),
migrations.AddField( migrations.AddField(
model_name='evento', model_name="evento",
name='total_participantes', 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'), 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, preserve_default=True,
), ),
] ]

12
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 import models, migrations
from django.db.models import Sum from django.db.models import Sum
def atualiza_participantes(apps, schema_editor): def atualiza_participantes(apps, schema_editor):
if schema_editor.connection.alias != 'default': if schema_editor.connection.alias != "default":
return return
Evento = apps.get_model('eventos', 'Evento') Evento = apps.get_model("eventos", "Evento")
for e in Evento.objects.all(): for e in Evento.objects.all():
total = e.convite_set.aggregate(total=Sum('qtde_participantes')) total = e.convite_set.aggregate(total=Sum("qtde_participantes"))
total = total['total'] total = total["total"]
if (total is not None) or (total > 0): if (total is not None) or (total > 0):
e.total_participantes = total e.total_participantes = total
e.save() e.save()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0011_auto_20211117_0633'), ("eventos", "0011_auto_20211117_0633"),
] ]
operations = [ operations = [

57
sigi/apps/eventos/migrations/0013_modelodeclaracao.py

@ -8,22 +8,61 @@ import tinymce.models
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0012_auto_20211117_0657'), ("eventos", "0012_auto_20211117_0657"),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='ModeloDeclaracao', name="ModeloDeclaracao",
fields=[ 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')), "id",
('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')])), models.AutoField(
('margem', models.PositiveIntegerField(default=4, help_text='Margem da p\xe1gina em cent\xedmetros', verbose_name='Margem')), verbose_name="ID",
('texto', tinymce.models.HTMLField(help_text='Use as seguintes marca\xe7\xf5es:<ul><li>{{ casa }} para o nome da Casa Legislativa / \xf3rg\xe3o</li><li>{{ nome }} para o nome do visitante</li><li>{{ data }} para a data de emiss\xe3o da declara\xe7\xe3o</li><li>{{ evento.data_inicio }} para a data/hora do in\xedcio da visita</li><li>{{ evento.data_termino }} para a data/hora do t\xe9rmino da visita</li><li>{{ evento.nome }} para o nome do evento</li><li>{{ evento.descricao }} para a descri\xe7\xe3o do evento</li></ul>', verbose_name='Texto da declara\xe7\xe3o')), 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:<ul><li>{{ casa }} para o nome da Casa Legislativa / \xf3rg\xe3o</li><li>{{ nome }} para o nome do visitante</li><li>{{ data }} para a data de emiss\xe3o da declara\xe7\xe3o</li><li>{{ evento.data_inicio }} para a data/hora do in\xedcio da visita</li><li>{{ evento.data_termino }} para a data/hora do t\xe9rmino da visita</li><li>{{ evento.nome }} para o nome do evento</li><li>{{ evento.descricao }} para a descri\xe7\xe3o do evento</li></ul>",
verbose_name="Texto da declara\xe7\xe3o",
),
),
], ],
options={ options={
'verbose_name': 'modelo de declara\xe7\xe3o', "verbose_name": "modelo de declara\xe7\xe3o",
'verbose_name_plural': 'modelos de declara\xe7\xe3o', "verbose_name_plural": "modelos de declara\xe7\xe3o",
}, },
bases=(models.Model,), bases=(models.Model,),
), ),

11
sigi/apps/eventos/migrations/0014_auto_20211124_0736.py

@ -8,14 +8,17 @@ import tinymce.models
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('eventos', '0013_modelodeclaracao'), ("eventos", "0013_modelodeclaracao"),
] ]
operations = [ operations = [
migrations.AlterField( migrations.AlterField(
model_name='modelodeclaracao', model_name="modelodeclaracao",
name='texto', name="texto",
field=tinymce.models.HTMLField(help_text='Use as seguintes marca\xe7\xf5es:<ul><li>{{ casa.nome }} para o nome da Casa Legislativa / \xf3rg\xe3o</li><li>{{ casa.municipio.uf.sigla }} para a sigla da UF da Casa legislativa</li><li>{{ nome }} para o nome do visitante</li><li>{{ data }} para a data de emiss\xe3o da declara\xe7\xe3o</li><li>{{ evento.data_inicio }} para a data/hora do in\xedcio da visita</li><li>{{ evento.data_termino }} para a data/hora do t\xe9rmino da visita</li><li>{{ evento.nome }} para o nome do evento</li><li>{{ evento.descricao }} para a descri\xe7\xe3o do evento</li></ul>', verbose_name='Texto da declara\xe7\xe3o'), field=tinymce.models.HTMLField(
help_text="Use as seguintes marca\xe7\xf5es:<ul><li>{{ casa.nome }} para o nome da Casa Legislativa / \xf3rg\xe3o</li><li>{{ casa.municipio.uf.sigla }} para a sigla da UF da Casa legislativa</li><li>{{ nome }} para o nome do visitante</li><li>{{ data }} para a data de emiss\xe3o da declara\xe7\xe3o</li><li>{{ evento.data_inicio }} para a data/hora do in\xedcio da visita</li><li>{{ evento.data_termino }} para a data/hora do t\xe9rmino da visita</li><li>{{ evento.nome }} para o nome do evento</li><li>{{ evento.descricao }} para a descri\xe7\xe3o do evento</li></ul>",
verbose_name="Texto da declara\xe7\xe3o",
),
preserve_default=True, preserve_default=True,
), ),
] ]

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save