Browse Source

Fix #20

pull/32/head
Sesostris Vieira 4 years ago
parent
commit
d6099d082c
  1. 22
      etc/migracao/migra.py
  2. 2
      locale/en/LC_MESSAGES/django.po
  3. 12
      scripts/importa_pesquisa.py
  4. 4
      scripts/verificacao_arquivos_faltando_media.py
  5. 126
      sigi/apps/casas/admin.py
  6. 13
      sigi/apps/casas/forms.py
  7. 6
      sigi/apps/casas/management/commands/importa_gerentes.py
  8. 31
      sigi/apps/casas/migrations/0014_auto_20210406_1945.py
  9. 28
      sigi/apps/casas/migrations/0015_auto_20210407_0801.py
  10. 20
      sigi/apps/casas/migrations/0016_auto_20210407_1559.py
  11. 51
      sigi/apps/casas/models.py
  12. 2
      sigi/apps/casas/reports.py
  13. 2
      sigi/apps/casas/templates/casas/lista_casas_carteira_snippet.html
  14. 4
      sigi/apps/casas/test_casas.py
  15. 28
      sigi/apps/casas/urls.py
  16. 36
      sigi/apps/casas/views.py
  17. 85
      sigi/apps/convenios/admin.py
  18. 21
      sigi/apps/convenios/migrations/0003_auto_20210406_1945.py
  19. 78
      sigi/apps/convenios/migrations/0004_auto_20210407_1928.py
  20. 26
      sigi/apps/convenios/migrations/0005_auto_20210409_0842.py
  21. 62
      sigi/apps/convenios/models.py
  22. 68
      sigi/apps/convenios/templates/convenios/change_list.html
  23. 4
      sigi/apps/convenios/views.py
  24. 10
      sigi/apps/diagnosticos/forms.py
  25. 21
      sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py
  26. 2
      sigi/apps/diagnosticos/models.py
  27. 6
      sigi/apps/diagnosticos/views.py
  28. 27
      sigi/apps/eventos/migrations/0005_auto_20210406_1945.py
  29. 6
      sigi/apps/eventos/models.py
  30. 16
      sigi/apps/home/templatetags/menu_conf.yaml
  31. 14
      sigi/apps/home/views.py
  32. 21
      sigi/apps/inventario/migrations/0002_auto_20210406_1945.py
  33. 2
      sigi/apps/inventario/models.py
  34. 21
      sigi/apps/metas/migrations/0002_auto_20210406_1945.py
  35. 4
      sigi/apps/metas/models.py
  36. 4
      sigi/apps/metas/templatetags/mapa_tags.py
  37. 10
      sigi/apps/metas/views.py
  38. 21
      sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py
  39. 2
      sigi/apps/ocorrencias/models.py
  40. 8
      sigi/apps/ocorrencias/views.py
  41. 27
      sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py
  42. 6
      sigi/apps/parlamentares/models.py
  43. 4
      sigi/apps/parlamentares/reports.py
  44. 2
      sigi/apps/parlamentares/views.py
  45. 9
      sigi/apps/servicos/admin.py
  46. 17
      sigi/apps/servicos/migrations/0004_delete_casaatendida.py
  47. 27
      sigi/apps/servicos/migrations/0005_auto_20210406_1945.py
  48. 25
      sigi/apps/servicos/migrations/0006_casaatendida.py
  49. 8
      sigi/apps/servicos/models.py
  50. 2
      sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html
  51. 9
      sigi/apps/servicos/views.py
  52. 6
      sigi/test_cart.py
  53. 4
      templates/admin/change_list.html

22
etc/migracao/migra.py

@ -71,7 +71,7 @@ def migra_assembleias(filename):
bairro = aux_end[1].replace(' ', '', 1) bairro = aux_end[1].replace(' ', '', 1)
else: else:
bairro = '' bairro = ''
casa = CasaLegislativa( casa = Orgao(
municipio=municipio, municipio=municipio,
nome=line[NOME_COL], nome=line[NOME_COL],
tipo=tipo_casa, tipo=tipo_casa,
@ -160,7 +160,7 @@ def migra_casas(filename):
bairro = '' bairro = ''
if(aux_end.__len__() > 1): if(aux_end.__len__() > 1):
bairro = aux_end[1].replace(' ', '', 1) bairro = aux_end[1].replace(' ', '', 1)
casa = CasaLegislativa( casa = Orgao(
municipio=municipio, municipio=municipio,
nome='Câmara Municipal de ' + line[NOME_COL], nome='Câmara Municipal de ' + line[NOME_COL],
tipo=tipo_casa, tipo=tipo_casa,
@ -214,11 +214,11 @@ def migra_cnpj(filename):
linenum += 1 linenum += 1
try: try:
casa = CasaLegislativa.objects.get(municipio__codigo_tse=line[COD_TSE_COL]) casa = Orgao.objects.get(municipio__codigo_tse=line[COD_TSE_COL])
except CasaLegislativa.DoesNotExist: except Orgao.DoesNotExist:
print ERROR_MSG_1 % (filename, linenum) print ERROR_MSG_1 % (filename, linenum)
continue continue
except CasaLegislativa.MultipleObjectsReturned: except Orgao.MultipleObjectsReturned:
print ERROR_MSG_1 % (filename, linenum) print ERROR_MSG_1 % (filename, linenum)
continue continue
except ValueError: except ValueError:
@ -271,12 +271,12 @@ def migra_convenios_casas(filename):
linenum += 1 linenum += 1
try: try:
casa = CasaLegislativa.objects.get(municipio__codigo_ibge=line[COD_IBGE_COL]) casa = Orgao.objects.get(municipio__codigo_ibge=line[COD_IBGE_COL])
except CasaLegislativa.DoesNotExist: except Orgao.DoesNotExist:
print "Erro ao inserir convênio. Casa não existe" print "Erro ao inserir convênio. Casa não existe"
print ERROR_MSG_1 % (filename, linenum) print ERROR_MSG_1 % (filename, linenum)
continue continue
except CasaLegislativa.MultipleObjectsReturned: except Orgao.MultipleObjectsReturned:
print ERROR_MSG_1 % (filename, linenum) print ERROR_MSG_1 % (filename, linenum)
continue continue
except ValueError: except ValueError:
@ -373,11 +373,11 @@ def migra_convenios_assembleias(filename):
linenum += 1 linenum += 1
try: try:
assembleia = CasaLegislativa.objects.get(municipio__uf__sigla=line[SIGLA_COL], tipo=tipo_casa) assembleia = Orgao.objects.get(municipio__uf__sigla=line[SIGLA_COL], tipo=tipo_casa)
except CasaLegislativa.DoesNotExist: except Orgao.DoesNotExist:
print ERROR_MSG_1 % (filename, linenum) print ERROR_MSG_1 % (filename, linenum)
continue continue
except CasaLegislativa.MultipleObjectsReturned: except Orgao.MultipleObjectsReturned:
print ERROR_MSG_1 % (filename, linenum) print ERROR_MSG_1 % (filename, linenum)
continue continue
except ValueError: except ValueError:

2
locale/en/LC_MESSAGES/django.po

@ -901,7 +901,7 @@ msgid "Data de Aceite"
msgstr "" msgstr ""
#: sigi/apps/convenios/reports.py:143 #: sigi/apps/convenios/reports.py:143
msgid "CasaLegislativa: " msgid "Orgao: "
msgstr "" msgstr ""
#: sigi/apps/convenios/reports.py:250 #: sigi/apps/convenios/reports.py:250

12
scripts/importa_pesquisa.py

@ -26,11 +26,11 @@ import csv
import urlparse import urlparse
from datetime import datetime from datetime import datetime
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
def importa(file_list): def importa(file_list):
''' Este script importa dados de um arquivo CSV e dá carga no model casas.CasaLegislativa ''' Este script importa dados de um arquivo CSV e dá carga no model casas.Orgao
O arquivo CSV esperado tem um cabeçalho de campos na primeira linha, com os seguintes campos: O arquivo CSV esperado tem um cabeçalho de campos na primeira linha, com os seguintes campos:
@ -74,11 +74,11 @@ def importa(file_list):
cidade = uf_cidade[5:] cidade = uf_cidade[5:]
if tem_portal.lower() == 'não': if tem_portal.lower() == 'não':
inclusao = CasaLegislativa.INCLUSAO_DIGITAL_CHOICES[1][0] inclusao = Orgao.INCLUSAO_DIGITAL_CHOICES[1][0]
elif pmodelo.lower() == 'não': elif pmodelo.lower() == 'não':
inclusao = CasaLegislativa.INCLUSAO_DIGITAL_CHOICES[3][0] inclusao = Orgao.INCLUSAO_DIGITAL_CHOICES[3][0]
else: else:
inclusao = CasaLegislativa.INCLUSAO_DIGITAL_CHOICES[2][0] inclusao = Orgao.INCLUSAO_DIGITAL_CHOICES[2][0]
l = url.splitlines() l = url.splitlines()
url = '' url = ''
@ -102,7 +102,7 @@ def importa(file_list):
else: else:
servidor = servidor[0] servidor = servidor[0]
casa = CasaLegislativa.objects.filter(tipo_id=1, municipio__uf__sigla=uf, municipio__nome__iexact=cidade) casa = Orgao.objects.filter(tipo_id=1, municipio__uf__sigla=uf, municipio__nome__iexact=cidade)
cc = casa.count() cc = casa.count()
if cc == 0: if cc == 0:
row.append('Municipio nao foi encontrado') row.append('Municipio nao foi encontrado')

4
scripts/verificacao_arquivos_faltando_media.py

@ -9,7 +9,7 @@ from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from terminaltables import AsciiTable from terminaltables import AsciiTable
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.convenios.models import Anexo as AnexoConvenios from sigi.apps.convenios.models import Anexo as AnexoConvenios
from sigi.apps.diagnosticos.models import Anexo as AnexoDiagnosticos from sigi.apps.diagnosticos.models import Anexo as AnexoDiagnosticos
from sigi.apps.ocorrencias.models import Anexo as AnexoOcorrencias from sigi.apps.ocorrencias.models import Anexo as AnexoOcorrencias
@ -31,7 +31,7 @@ def url(obj):
# IMAGENS FALTANDO # IMAGENS FALTANDO
imagens_faltando = [[u"SITUAÇÃO DO ARQUIVO DA FOTO ", "URL", "OBJETO"]] imagens_faltando = [[u"SITUAÇÃO DO ARQUIVO DA FOTO ", "URL", "OBJETO"]]
for cl in (CasaLegislativa, Parlamentar, Servidor): for cl in (Orgao, Parlamentar, Servidor):
for a in cl.objects.all(): for a in cl.objects.all():
if a.foto: if a.foto:
imagens_faltando.append([ imagens_faltando.append([

126
sigi/apps/casas/admin.py

@ -8,18 +8,18 @@ from django.shortcuts import render
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from image_cropping import ImageCroppingMixin from image_cropping import ImageCroppingMixin
from sigi.apps.casas.forms import CasaLegislativaForm from sigi.apps.casas.forms import OrgaoForm
from sigi.apps.casas.models import CasaLegislativa, Presidente, Funcionario, TipoOrgao from sigi.apps.casas.models import Orgao, Presidente, Funcionario, TipoOrgao
from sigi.apps.casas.views import report_complete, labels_report, export_csv, \ from sigi.apps.casas.views import report_complete, labels_report, export_csv, \
labels_report_sem_presidente, report, \ labels_report_sem_presidente, report, \
adicionar_casas_carrinho adicionar_casas_carrinho
from sigi.apps.contatos.models import Telefone from sigi.apps.contatos.models import Telefone
from sigi.apps.convenios.models import Convenio, Projeto from sigi.apps.convenios.models import Convenio, Projeto
from sigi.apps.diagnosticos.models import Diagnostico # from sigi.apps.diagnosticos.models import Diagnostico
from sigi.apps.inventario.models import Bem # from sigi.apps.inventario.models import Bem
from sigi.apps.metas.models import PlanoDiretor from sigi.apps.metas.models import PlanoDiretor
from sigi.apps.ocorrencias.models import Ocorrencia from sigi.apps.ocorrencias.models import Ocorrencia
from sigi.apps.parlamentares.models import Legislatura # from sigi.apps.parlamentares.models import Legislatura
from sigi.apps.servicos.models import Servico, TipoServico from sigi.apps.servicos.models import Servico, TipoServico
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
from sigi.apps.utils import queryset_ascii from sigi.apps.utils import queryset_ascii
@ -129,7 +129,7 @@ class ConveniosInline(admin.TabularInline):
return "" return ""
status = obj.get_status() status = obj.get_status()
if status in [u"Vencido", u"Desistência"]: if status in [u"Vencido", u"Desistência", u"Cancelado"]:
label = r"danger" label = r"danger"
elif status == u"Vigente": elif status == u"Vigente":
label = r"success" label = r"success"
@ -164,51 +164,47 @@ class ConveniosInline(admin.TabularInline):
link_sigad.short_description = _("Processo no Senado") link_sigad.short_description = _("Processo no Senado")
link_sigad.allow_tags = True link_sigad.allow_tags = True
# class LegislaturaInline(admin.TabularInline):
class LegislaturaInline(admin.TabularInline): # model = Legislatura
model = Legislatura # fields = ['numero', 'data_inicio', 'data_fim', 'data_eleicao', 'total_parlamentares', 'link_parlamentares', ]
fields = ['numero', 'data_inicio', 'data_fim', 'data_eleicao', 'total_parlamentares', 'link_parlamentares', ] # readonly_fields = ['link_parlamentares', ]
readonly_fields = ['link_parlamentares', ]
# def link_parlamentares(self, obj):
def link_parlamentares(self, obj): # if obj.pk is None:
if obj.pk is None: # return ""
return "" # from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse # url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=[obj.pk])
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=[obj.pk]) # url = url + '?_popup=1'
url = url + '?_popup=1' # return """<input id="edit_legislatura-%s" type="hidden"/>
return """<input id="edit_legislatura-%s" type="hidden"/> # <a id="lookup_edit_legislatura-%s" href="%s" class="changelink" onclick="return showRelatedObjectLookupPopup(this)">
<a id="lookup_edit_legislatura-%s" href="%s" class="changelink" onclick="return showRelatedObjectLookupPopup(this)"> # Editar
Editar # </a>""" % (obj.pk, obj.pk, url)
</a>""" % (obj.pk, obj.pk, url)
# link_parlamentares.short_description = _(u'Parlamentares')
link_parlamentares.short_description = _(u'Parlamentares') # link_parlamentares.allow_tags = True
link_parlamentares.allow_tags = True
# class DiagnosticoInline(admin.TabularInline):
# model = Diagnostico
class DiagnosticoInline(admin.TabularInline): # fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ]
model = Diagnostico # readonly_fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ]
fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ] # extra = 0
readonly_fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ] # max_num = 0
extra = 0 # can_delete = False
max_num = 0
can_delete = False # def link_diagnostico(self, obj):
# if obj.pk is None:
def link_diagnostico(self, obj): # return ""
if obj.pk is None: # url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=["%s.pdf" % obj.pk])
return "" # return """<input id="edit_diagnostico-%s" type="hidden"/>
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=["%s.pdf" % obj.pk]) # <a id="lookup_edit_diagnostico-%s" href="%s" class="button" target="_blank">
return """<input id="edit_diagnostico-%s" type="hidden"/> # Abrir PDF
<a id="lookup_edit_diagnostico-%s" href="%s" class="button" target="_blank"> # </a>""" % (obj.pk, obj.pk, url)
Abrir PDF
</a>""" % (obj.pk, obj.pk, url) # link_diagnostico.short_description = _(u'Ver PDF')
# link_diagnostico.allow_tags = True
link_diagnostico.short_description = _(u'Ver PDF')
link_diagnostico.allow_tags = True # class BemInline(admin.TabularInline):
# model = Bem
class BemInline(admin.TabularInline):
model = Bem
class ServicoInline(admin.TabularInline): class ServicoInline(admin.TabularInline):
model = Servico model = Servico
@ -218,10 +214,8 @@ class ServicoInline(admin.TabularInline):
max_num = 0 max_num = 0
can_delete = False can_delete = False
# class PlanoDiretorInline(admin.TabularInline):
class PlanoDiretorInline(admin.TabularInline): # model = PlanoDiretor
model = PlanoDiretor
class OcorrenciaInline(admin.TabularInline): class OcorrenciaInline(admin.TabularInline):
model = Ocorrencia model = Ocorrencia
@ -309,12 +303,11 @@ class ServicoFilter(admin.SimpleListFilter):
return queryset.distinct('municipio__uf__nome', 'nome') return queryset.distinct('municipio__uf__nome', 'nome')
class CasaLegislativaAdmin(ImageCroppingMixin, BaseModelAdmin): class OrgaoAdmin(ImageCroppingMixin, BaseModelAdmin):
form = CasaLegislativaForm form = OrgaoForm
actions = ['adicionar_casas', ] actions = ['adicionar_casas', ]
inlines = (TelefonesInline, PresidenteInline, FuncionariosInline, inlines = (TelefonesInline, PresidenteInline, FuncionariosInline,
ConveniosInline, LegislaturaInline, DiagnosticoInline, BemInline, ConveniosInline, ServicoInline, OcorrenciaInline,)
ServicoInline, PlanoDiretorInline, OcorrenciaInline,)
list_display = ('nome', 'get_uf', 'get_gerentes', 'get_convenios', list_display = ('nome', 'get_uf', 'get_gerentes', 'get_convenios',
'get_servicos') 'get_servicos')
list_display_links = ('nome',) list_display_links = ('nome',)
@ -342,7 +335,7 @@ class CasaLegislativaAdmin(ImageCroppingMixin, BaseModelAdmin):
}), }),
) )
raw_id_fields = ('municipio',) raw_id_fields = ('municipio',)
readonly_fields = ['num_parlamentares', ] readonly_fields = ['num_parlamentares', 'gerentes_interlegis',]
search_fields = ('search_text', 'cnpj', 'bairro', 'logradouro', search_fields = ('search_text', 'cnpj', 'bairro', 'logradouro',
'cep', 'municipio__nome', 'municipio__uf__nome', 'cep', 'municipio__nome', 'municipio__uf__nome',
'municipio__codigo_ibge', 'pagina_web', 'observacoes') 'municipio__codigo_ibge', 'pagina_web', 'observacoes')
@ -374,14 +367,17 @@ class CasaLegislativaAdmin(ImageCroppingMixin, BaseModelAdmin):
get_servicos.allow_tags = True get_servicos.allow_tags = True
def changelist_view(self, request, extra_context=None): def changelist_view(self, request, extra_context=None):
return super(CasaLegislativaAdmin, self).changelist_view( return super(OrgaoAdmin, self).changelist_view(
request, request,
extra_context={'query_str': '?' + request.META['QUERY_STRING']} extra_context={'query_str': '?' + request.META['QUERY_STRING']}
) )
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return super(CasaLegislativaAdmin, self).lookup_allowed(lookup, value) or \ return (super(OrgaoAdmin, self).lookup_allowed(lookup, value) or
lookup in ['municipio__uf__codigo_ibge__exact', 'convenio__projeto__id__exact'] lookup in ['tipo__legislativo__exact',
'tipo__sigla__exact',
'municipio__uf__codigo_ibge__exact',
'convenio__projeto__id__exact'])
def etiqueta(self, request, queryset): def etiqueta(self, request, queryset):
return labels_report(request, queryset=queryset) return labels_report(request, queryset=queryset)
@ -426,11 +422,11 @@ class CasaLegislativaAdmin(ImageCroppingMixin, BaseModelAdmin):
adicionar_casas.short_description = _(u"Armazenar casas no carrinho para exportar") adicionar_casas.short_description = _(u"Armazenar casas no carrinho para exportar")
def get_actions(self, request): def get_actions(self, request):
actions = super(CasaLegislativaAdmin, 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(CasaLegislativa, CasaLegislativaAdmin) admin.site.register(Orgao, OrgaoAdmin)
admin.site.register(TipoOrgao) admin.site.register(TipoOrgao)

13
sigi/apps/casas/forms.py

@ -3,11 +3,11 @@ from django import forms
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from localflavor.br.forms import BRZipCodeField from localflavor.br.forms import BRZipCodeField
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
class CasaLegislativaForm(forms.ModelForm): class OrgaoForm(forms.ModelForm):
# cnpj = BRCNPJField( # cnpj = BRCNPJField(
# label=_(u'CNPJ'), # label=_(u'CNPJ'),
# required=False, # required=False,
@ -16,9 +16,16 @@ class CasaLegislativaForm(forms.ModelForm):
cep = BRZipCodeField(label=_(u'CEP'), help_text=_(u'Formato') + ': <em>XXXXX-XXX</em>.') cep = BRZipCodeField(label=_(u'CEP'), help_text=_(u'Formato') + ': <em>XXXXX-XXX</em>.')
class Meta: class Meta:
model = CasaLegislativa model = Orgao
fields = '__all__' fields = '__all__'
# def clean(self):
# cleaned_data = super(OrgaoForm, self).clean()
# tipo = cleaned_data.get('tipo')
# municipio = cleaned_data.get('municipio')
# if tipo.legislativo:
# if Orgao.objects.filter(tipo=tipo)
class PortfolioForm(forms.Form): class PortfolioForm(forms.Form):
ACAO_CHOICES = ( ACAO_CHOICES = (
('ADD', _(u"Adicionar")), ('ADD', _(u"Adicionar")),

6
sigi/apps/casas/management/commands/importa_gerentes.py

@ -25,7 +25,7 @@
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.casas.models import CasaLegislativa 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
@ -56,7 +56,7 @@ class Command(BaseCommand):
if not self.campos.issubset(reader.fieldnames): if not self.campos.issubset(reader.fieldnames):
raise CommandError(u"O arquivo não possui todos os campos obrigatórios") raise CommandError(u"O arquivo não possui todos os campos obrigatórios")
CasaLegislativa.gerentes_interlegis.through.objects.all().delete() Orgao.gerentes_interlegis.through.objects.all().delete()
erros = 0 erros = 0
@ -87,7 +87,7 @@ class Command(BaseCommand):
erros = erros + 1 erros = erros + 1
continue continue
for casa in municipio.casalegislativa_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()

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

@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import image_cropping.fields
import sigi.apps.utils
class Migration(migrations.Migration):
dependencies = [
# ('metas', '0002_auto_20210406_1945'),
('contatos', '0002_auto_20151104_0810'),
('servidores', '0001_initial'),
# ('parlamentares', '0002_auto_20210406_1945'),
# ('servicos', '0005_auto_20210406_1945'),
('servicos', '0004_delete_casaatendida'),
# ('inventario', '0002_auto_20210406_1945'),
# ('convenios', '0003_auto_20210406_1945'),
# ('ocorrencias', '0003_auto_20210406_1945'),
# ('diagnosticos', '0004_auto_20210406_1945'),
# ('eventos', '0005_auto_20210406_1945'),
('casas', '0013_auto_20210406_1428'),
]
operations = [
migrations.RenameModel(
old_name='CasaLegislativa',
new_name='Orgao',
),
]

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

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

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

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('casas', '0015_auto_20210407_0801'),
]
operations = [
migrations.AlterField(
model_name='orgao',
name='gerentes_interlegis',
field=models.ManyToManyField(related_name='casas_que_gerencia', verbose_name='Gerentes Interlegis', to='servidores.Servidor', blank=True),
preserve_default=True,
),
]

51
sigi/apps/casas/models.py

@ -3,6 +3,7 @@ from datetime import datetime
import random import random
from string import ascii_uppercase from string import ascii_uppercase
from unicodedata import normalize from unicodedata import normalize
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.contrib.contenttypes import generic from django.contrib.contenttypes import generic
from django.db import models from django.db import models
@ -12,9 +13,7 @@ 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):
""" Modelo para representar o tipo da Casa Legislativa """ Modelo para representar o tipo da Casa Legislativa
Geralmente: Câmara Municipal, Assembléia Legislativa, Geralmente: Câmara Municipal, Assembléia Legislativa,
@ -23,6 +22,7 @@ class TipoOrgao(models.Model):
sigla = models.CharField(_(u"Sigla"), max_length=5) sigla = models.CharField(_(u"Sigla"), max_length=5)
nome = models.CharField(_(u"Nome"), max_length=100) nome = models.CharField(_(u"Nome"), max_length=100)
legislativo = models.BooleanField(_(u"Poder legislativo"), default=False)
class Meta: class Meta:
verbose_name = _(u"Tipo de órgão") verbose_name = _(u"Tipo de órgão")
@ -31,9 +31,7 @@ class TipoOrgao(models.Model):
def __unicode__(self): def __unicode__(self):
return self.nome return self.nome
class Orgao(models.Model):
class CasaLegislativa(models.Model):
""" Modelo para representar uma Casa Legislativa """ Modelo para representar uma Casa Legislativa
""" """
@ -72,7 +70,8 @@ class CasaLegislativa(models.Model):
gerentes_interlegis = models.ManyToManyField( gerentes_interlegis = models.ManyToManyField(
Servidor, Servidor,
verbose_name=_(u"Gerentes Interlegis"), verbose_name=_(u"Gerentes Interlegis"),
related_name='casas_que_gerencia' related_name='casas_que_gerencia',
blank=True,
) )
# Informações de contato # Informações de contato
@ -143,9 +142,8 @@ class CasaLegislativa(models.Model):
class Meta: class Meta:
ordering = ('nome',) ordering = ('nome',)
unique_together = ('municipio', 'tipo') verbose_name = _(u'Órgão')
verbose_name = _(u'Casa Legislativa') verbose_name_plural = _(u'Órgãos')
verbose_name_plural = _(u'Casas Legislativas')
def lista_gerentes(self, fmt='html'): def lista_gerentes(self, fmt='html'):
if not self.gerentes_interlegis.exists(): if not self.gerentes_interlegis.exists():
@ -210,7 +208,7 @@ class CasaLegislativa(models.Model):
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 CasaLegislativa.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
self.save() self.save()
@ -243,7 +241,7 @@ class CasaLegislativa(models.Model):
cityName = cityName.replace(' ', '') cityName = cityName.replace(' ', '')
ultima = len(cityName) ultima = len(cityName)
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \ while Orgao.objects.filter(codigo_interlegis=codigo). \
count() > 0 and ultima > 0: count() > 0 and ultima > 0:
codigo = codigo[:2] + cityName[ultima - 1: ultima] codigo = codigo[:2] + cityName[ultima - 1: ultima]
ultima -= 1 ultima -= 1
@ -252,11 +250,11 @@ class CasaLegislativa(models.Model):
# não gerou um código único, então vamos compor o nome usando as # não gerou um código único, então vamos compor o nome usando as
# três primeiras consoantes. # três primeiras consoantes.
if CasaLegislativa.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 = cityName.replace('A', '').replace('E', '').\
replace('I', '').replace('O', '').replace('U', '')[:3] replace('I', '').replace('O', '').replace('U', '')[:3]
if len(codigo_cons) == 3 and \ if len(codigo_cons) == 3 and \
CasaLegislativa.objects.filter(codigo_interlegis=codigo).count() > 0: 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
@ -264,7 +262,7 @@ class CasaLegislativa(models.Model):
i = 'A' i = 'A'
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \ while Orgao.objects.filter(codigo_interlegis=codigo). \
count() > 0 and i <= 'Z': 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)
@ -275,7 +273,7 @@ class CasaLegislativa(models.Model):
i = 0 i = 0
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \ while Orgao.objects.filter(codigo_interlegis=codigo). \
count() > 0 and i < 100: count() > 0 and i < 100:
codigo = random.choice(cityName) + random.choice(cityName) + \ codigo = random.choice(cityName) + random.choice(cityName) + \
random.choice(cityName) random.choice(cityName)
@ -286,10 +284,8 @@ class CasaLegislativa(models.Model):
i = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' i = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \ while Orgao.objects.filter(codigo_interlegis=codigo).count() > 0:
count() > 0: codigo = random.choice(i) + random.choice(i) + random.choice(i)
codigo = random.choice(i) + random.choice(i) + \
random.choice(i)
self.codigo_interlegis = codigo self.codigo_interlegis = codigo
self.save() self.save()
@ -299,11 +295,22 @@ class CasaLegislativa(models.Model):
def __unicode__(self): def __unicode__(self):
return self.nome return self.nome
def clean(self):
if (hasattr(self, 'tipo') and hasattr(self, 'municipio')
and self.tipo.legislativo):
if Orgao.objects.filter(
tipo=self.tipo,
municipio=self.municipio).exclude(pk=self.pk).exists():
raise ValidationError(
_(u"Já existe um(a) %(tipo)s em %(municipio)s"),
code='integrity',
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 = CasaLegislativa.objects.get(pk=self.pk) original = Orgao.objects.get(pk=self.pk)
if (self.logradouro != original.logradouro or if (self.logradouro != original.logradouro or
self.bairro != original.bairro or self.bairro != original.bairro or
self.municipio != original.municipio or self.municipio != original.municipio or
@ -315,7 +322,7 @@ class CasaLegislativa(models.Model):
if address_changed: if address_changed:
self.ult_alt_endereco = datetime.now() self.ult_alt_endereco = datetime.now()
return super(CasaLegislativa, self).save(*args, **kwargs) return super(Orgao, self).save(*args, **kwargs)
class Funcionario(models.Model): class Funcionario(models.Model):
@ -343,7 +350,7 @@ class Funcionario(models.Model):
("F", _(u"Feminino")) ("F", _(u"Feminino"))
] ]
casa_legislativa = models.ForeignKey(CasaLegislativa) casa_legislativa = models.ForeignKey(Orgao)
nome = models.CharField(_(u'nome completo'), max_length=60, blank=False) nome = models.CharField(_(u'nome completo'), max_length=60, blank=False)
# nome.alphabetic_filter = True # nome.alphabetic_filter = True
sexo = models.CharField( sexo = models.CharField(

2
sigi/apps/casas/reports.py

@ -52,7 +52,7 @@ class CasasLegislativasLabels(Report):
Usage example:: Usage example::
>>> from geraldo.generators import PDFGenerator >>> from geraldo.generators import PDFGenerator
>>> queryset = CasaLegislativa.objects.filter(municipio__uf__sigla='MG') >>> queryset = Orgao.objects.filter(municipio__uf__sigla='MG')
>>> report = LabelsReport(queryset) >>> report = LabelsReport(queryset)
>>> report.generate_by(PDFGenerator, filename='./inline-detail-report.pdf') >>> report.generate_by(PDFGenerator, filename='./inline-detail-report.pdf')

2
sigi/apps/casas/templates/casas/lista_casas_carteira_snippet.html

@ -64,7 +64,7 @@
</tr> </tr>
{% for casa in page_obj.object_list %} {% for casa in page_obj.object_list %}
<tr> <tr>
<td><a href="{% url 'admin:casas_casalegislativa_change' casa.pk %}">{{ casa.nome }}</a></td> <td><a href="{% url 'admin:casas_orgao_change' casa.pk %}">{{ casa.nome }}</a></td>
<td>{{ casa.municipio.uf.get_regiao_display }}</td> <td>{{ casa.municipio.uf.get_regiao_display }}</td>
<td>{{ casa.municipio.uf }}</td> <td>{{ casa.municipio.uf }}</td>
<td>{{ casa.municipio.microrregiao.mesorregiao }}</td> <td>{{ casa.municipio.microrregiao.mesorregiao }}</td>

4
sigi/apps/casas/test_casas.py

@ -1,7 +1,7 @@
import pytest import pytest
from django_dynamic_fixture import G from django_dynamic_fixture import G
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
@pytest.fixture @pytest.fixture
@ -14,4 +14,4 @@ def some_parliaments():
def parliaments_from_names(names): def parliaments_from_names(names):
return [G(CasaLegislativa, nome=name, foto=None,) for name in names] return [G(Orgao, nome=name, foto=None,) for name in names]

28
sigi/apps/casas/urls.py

@ -6,33 +6,33 @@ urlpatterns = patterns(
'sigi.apps.casas.views', 'sigi.apps.casas.views',
# Informacoes de uma casa legislativa # Informacoes de uma casa legislativa
url(r'^casalegislativa/report_complete/$', 'report_complete', name='report-complete-all'), url(r'^orgao/report_complete/$', 'report_complete', name='report-complete-all'),
url(r'^casalegislativa/(?P<id>\w+)/report_complete/$', 'report_complete', name='report-complete-id'), url(r'^orgao/(?P<id>\w+)/report_complete/$', 'report_complete', name='report-complete-id'),
# Reports Labels # Reports Labels
url(r'^casalegislativa/labels/$', 'labels_report', name='labels-report-all'), url(r'^orgao/labels/$', 'labels_report', name='labels-report-all'),
url(r'^casalegislativa/(?P<id>\w+)/labels/$', 'labels_report', name='labels-report-id'), url(r'^orgao/(?P<id>\w+)/labels/$', 'labels_report', name='labels-report-id'),
# Reports Labels Parlamentar # Reports Labels Parlamentar
url(r'^casalegislativa/labels_parlamentar/$', 'labels_report_parlamentar', name='lebels-report-parlamentar-all'), url(r'^orgao/labels_parlamentar/$', 'labels_report_parlamentar', name='lebels-report-parlamentar-all'),
url(r'^casalegislativa/(?P<id>\w+)/labels_parlamentar/$', 'labels_report_parlamentar', name='labels-report-parlamentar-id'), url(r'^orgao/(?P<id>\w+)/labels_parlamentar/$', 'labels_report_parlamentar', name='labels-report-parlamentar-id'),
# Reports labels sem presidente # Reports labels sem presidente
url(r'^casalegislativa/labels_sem_presidente/$', 'labels_report_sem_presidente', name='labels-report-sem-presidente-all'), url(r'^orgao/labels_sem_presidente/$', 'labels_report_sem_presidente', name='labels-report-sem-presidente-all'),
url(r'^casalegislativa/(?P<id>\w+)/labels_sem_presidente/$', 'labels_report_sem_presidente', name='labels-report-sem-presidente-id'), url(r'^orgao/(?P<id>\w+)/labels_sem_presidente/$', 'labels_report_sem_presidente', name='labels-report-sem-presidente-id'),
# Reports casas sem convenio # Reports casas sem convenio
url(r'^casalegislativa/reports/$', 'report', name='casa-report'), url(r'^orgao/reports/$', 'report', name='casa-report'),
url(r'^casalegislativa/casas_sem_convenio_report/$', 'casas_sem_convenio_report', name='casas-sem-convenio-report'), url(r'^orgao/casas_sem_convenio_report/$', 'casas_sem_convenio_report', name='casas-sem-convenio-report'),
# CSV # CSV
url(r'^casalegislativa/csv/$', 'export_csv', name='casa-export-csv'), # Error url(r'^orgao/csv/$', 'export_csv', name='casa-export-csv'), # Error
# Carrinho # Carrinho
url(r'^casalegislativa/carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'), url(r'^orgao/carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'),
url(r'^casalegislativa/carrinho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-carrinho'), # Error url(r'^orgao/carrinho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-carrinho'), # Error
url(r'^casalegislativa/carrinho/deleta_itens_carrinho$', 'deleta_itens_carrinho', name='deleta-itens-carrinho'), # Error url(r'^orgao/carrinho/deleta_itens_carrinho$', 'deleta_itens_carrinho', name='deleta-itens-carrinho'), # Error
url(r'^portfolio/$', 'portfolio', name='casas-portfolio'), url(r'^portfolio/$', 'portfolio', name='casas-portfolio'),
url(r'^carteira/$', 'painel_relacionamento', name='casas-carteira'), url(r'^carteira/$', 'painel_relacionamento', name='casas-carteira'),
) )

36
sigi/apps/casas/views.py

@ -11,7 +11,7 @@ from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext as _, ungettext from django.utils.translation import ugettext as _, ungettext
from sigi.apps.casas.forms import PortfolioForm from sigi.apps.casas.forms import PortfolioForm
from sigi.apps.casas.models import CasaLegislativa, TipoOrgao from sigi.apps.casas.models import Orgao, TipoOrgao
from sigi.apps.casas.reports import (CasasLegislativasLabels, from sigi.apps.casas.reports import (CasasLegislativasLabels,
CasasLegislativasLabelsSemPresidente) CasasLegislativasLabelsSemPresidente)
from sigi.apps.contatos.models import UnidadeFederativa, Mesorregiao, Microrregiao from sigi.apps.contatos.models import UnidadeFederativa, Mesorregiao, Microrregiao
@ -25,8 +25,8 @@ from sigi.shortcuts import render_to_pdf
# @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 CasaLegislativaAdmin from sigi.apps.casas.admin import OrgaoAdmin
list_display = CasaLegislativaAdmin.list_display list_display = OrgaoAdmin.list_display
order_fields = [] order_fields = []
for order_number in o.split('.'): for order_number in o.split('.'):
@ -95,9 +95,9 @@ def carrinhoOrGet_for_qs(request):
""" """
if 'carrinho_casas' in request.session: if 'carrinho_casas' in request.session:
ids = request.session['carrinho_casas'] ids = request.session['carrinho_casas']
qs = CasaLegislativa.objects.filter(pk__in=ids) qs = Orgao.objects.filter(pk__in=ids)
else: else:
qs = CasaLegislativa.objects.all() qs = Orgao.objects.all()
if request.GET: if request.GET:
qs = get_for_qs(request.GET, qs) qs = get_for_qs(request.GET, qs)
return qs return qs
@ -189,7 +189,7 @@ def labels_report(request, id=None, tipo=None, formato='3x9_etiqueta'):
return labels_report_sem_presidente(request, id, formato) return labels_report_sem_presidente(request, id, formato)
if id: if id:
qs = CasaLegislativa.objects.filter(pk=id) qs = Orgao.objects.filter(pk=id)
else: else:
qs = carrinhoOrGet_for_qs(request) qs = carrinhoOrGet_for_qs(request)
@ -214,7 +214,7 @@ def labels_report_parlamentar(request, id=None, formato='3x9_etiqueta'):
formato = request.POST['tamanho_etiqueta'] formato = request.POST['tamanho_etiqueta']
if id: if id:
legislaturas = [c.legislatura_set.latest('data_inicio') for c in CasaLegislativa.objects.filter(pk__in=id, legislatura__id__isnull=False).distinct()] legislaturas = [c.legislatura_set.latest('data_inicio') for c in Orgao.objects.filter(pk__in=id, legislatura__id__isnull=False).distinct()]
mandatos = reduce(lambda x, y: x | y, [l.mandato_set.all() for l in legislaturas]) mandatos = reduce(lambda x, y: x | y, [l.mandato_set.all() for l in legislaturas])
parlamentares = [m.parlamentar for m in mandatos] parlamentares = [m.parlamentar for m in mandatos]
qs = parlamentares qs = parlamentares
@ -239,12 +239,12 @@ def carrinhoOrGet_for_parlamentar_qs(request):
""" """
if 'carrinho_casas' in request.session: if 'carrinho_casas' in request.session:
ids = request.session['carrinho_casas'] ids = request.session['carrinho_casas']
legislaturas = [c.legislatura_set.latest('data_inicio') for c in CasaLegislativa.objects.filter(pk__in=ids, legislatura__id__isnull=False).distinct()] legislaturas = [c.legislatura_set.latest('data_inicio') for c in Orgao.objects.filter(pk__in=ids, legislatura__id__isnull=False).distinct()]
mandatos = reduce(lambda x, y: x | y, [l.mandato_set.all() for l in legislaturas]) mandatos = reduce(lambda x, y: x | y, [l.mandato_set.all() for l in legislaturas])
parlamentares = [m.parlamentar for m in mandatos] parlamentares = [m.parlamentar for m in mandatos]
qs = parlamentares qs = parlamentares
else: else:
legislaturas = [c.legislatura_set.latest('data_inicio') for c in CasaLegislativa.objects.all().distinct()] legislaturas = [c.legislatura_set.latest('data_inicio') for c in Orgao.objects.all().distinct()]
mandatos = reduce(lambda x, y: x | y, [l.mandato_set.all() for l in legislaturas]) mandatos = reduce(lambda x, y: x | y, [l.mandato_set.all() for l in legislaturas])
parlamentares = [m.parlamentar for m in mandatos] parlamentares = [m.parlamentar for m in mandatos]
qs = parlamentares qs = parlamentares
@ -259,7 +259,7 @@ def labels_report_sem_presidente(request, id=None, formato='2x5_etiqueta'):
""" """
if id: if id:
qs = CasaLegislativa.objects.filter(pk=id) qs = Orgao.objects.filter(pk=id)
else: else:
qs = carrinhoOrGet_for_qs(request) qs = carrinhoOrGet_for_qs(request)
@ -285,7 +285,7 @@ def report(request, id=None, tipo=None):
return report_complete(request, id) return report_complete(request, id)
if id: if id:
qs = CasaLegislativa.objects.filter(pk=id) qs = Orgao.objects.filter(pk=id)
else: else:
qs = carrinhoOrGet_for_qs(request) qs = carrinhoOrGet_for_qs(request)
@ -302,7 +302,7 @@ def report(request, id=None, tipo=None):
def report_complete(request, id=None): def report_complete(request, id=None):
if id: if id:
qs = CasaLegislativa.objects.filter(pk=id) qs = Orgao.objects.filter(pk=id)
else: else:
qs = carrinhoOrGet_for_qs(request) qs = carrinhoOrGet_for_qs(request)
@ -314,7 +314,7 @@ def report_complete(request, id=None):
@login_required @login_required
def casas_sem_convenio_report(request): def casas_sem_convenio_report(request):
qs = CasaLegislativa.objects.filter(convenio=None).order_by('municipio__uf', 'nome') qs = Orgao.objects.filter(convenio=None).order_by('municipio__uf', 'nome')
if request.GET: if request.GET:
qs = get_for_qs(request.GET, qs) qs = get_for_qs(request.GET, qs)
@ -454,7 +454,7 @@ def portfolio(request):
name=unicode(microrregiao)) name=unicode(microrregiao))
) )
data['querystring'] = 'micro={0}'.format(microrregiao.pk) data['querystring'] = 'micro={0}'.format(microrregiao.pk)
casas = CasaLegislativa.objects.filter( casas = Orgao.objects.filter(
municipio__microrregiao=microrregiao municipio__microrregiao=microrregiao
) )
elif meso_id: elif meso_id:
@ -470,7 +470,7 @@ def portfolio(request):
_(u'Atribuir casas da mesorregiao {name} para').format( _(u'Atribuir casas da mesorregiao {name} para').format(
name=unicode(mesorregiao))) name=unicode(mesorregiao)))
data['querystring'] = 'meso={0}'.format(mesorregiao.pk) data['querystring'] = 'meso={0}'.format(mesorregiao.pk)
casas = CasaLegislativa.objects.filter( casas = Orgao.objects.filter(
municipio__microrregiao__mesorregiao=mesorregiao municipio__microrregiao__mesorregiao=mesorregiao
) )
elif uf_id: elif uf_id:
@ -483,7 +483,7 @@ def portfolio(request):
_(u'Atribuir casas do estado {name} para').format( _(u'Atribuir casas do estado {name} para').format(
name=unicode(uf))) name=unicode(uf)))
data['querystring'] = 'uf={0}'.format(uf.pk) data['querystring'] = 'uf={0}'.format(uf.pk)
casas = CasaLegislativa.objects.filter(municipio__uf=uf) casas = Orgao.objects.filter(municipio__uf=uf)
elif regiao: elif regiao:
data['regiao'] = regiao data['regiao'] = regiao
data['ufs'] = UnidadeFederativa.objects.filter(regiao=regiao) data['ufs'] = UnidadeFederativa.objects.filter(regiao=regiao)
@ -492,7 +492,7 @@ def portfolio(request):
name=[x[1] for x in UnidadeFederativa.REGIAO_CHOICES if name=[x[1] for x in UnidadeFederativa.REGIAO_CHOICES if
x[0] == regiao][0])) x[0] == regiao][0]))
data['querystring'] = 'regiao={0}'.format(regiao) data['querystring'] = 'regiao={0}'.format(regiao)
casas = CasaLegislativa.objects.filter(municipio__uf__regiao=regiao) casas = Orgao.objects.filter(municipio__uf__regiao=regiao)
if casas: if casas:
casas = casas.order_by('municipio__uf', casas = casas.order_by('municipio__uf',
@ -687,7 +687,7 @@ def painel_relacionamento(request):
casas = gerente.casas_que_gerencia.all() casas = gerente.casas_que_gerencia.all()
if gerente is None or not casas.exists(): if gerente is None or not casas.exists():
casas = CasaLegislativa.objects.exclude(gerentes_interlegis=None) casas = Orgao.objects.exclude(gerentes_interlegis=None)
gerente = None gerente = None
tipos_servico = TipoServico.objects.all() tipos_servico = TipoServico.objects.all()

85
sigi/apps/convenios/admin.py

@ -4,29 +4,27 @@ from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from geraldo.generators import PDFGenerator from geraldo.generators import PDFGenerator
from sigi.apps.convenios.models import Projeto, Convenio, EquipamentoPrevisto, Anexo, Tramitacao from sigi.apps.convenios.models import (Projeto, StatusConvenio, Convenio,
EquipamentoPrevisto, Anexo, Tramitacao)
from sigi.apps.convenios.reports import ConvenioReport from sigi.apps.convenios.reports import ConvenioReport
from sigi.apps.convenios.views import adicionar_convenios_carrinho from sigi.apps.convenios.views import adicionar_convenios_carrinho
from sigi.apps.utils import queryset_ascii from sigi.apps.utils import queryset_ascii
from sigi.apps.utils.base_admin import BaseModelAdmin from sigi.apps.utils.base_admin import BaseModelAdmin
from sigi.apps.servidores.models import Servidor
# class TramitacaoInline(admin.TabularInline):
class TramitacaoInline(admin.TabularInline): # model = Tramitacao
model = Tramitacao # extra = 1
extra = 1
class AnexosInline(admin.TabularInline): class AnexosInline(admin.TabularInline):
model = Anexo model = Anexo
extra = 2 extra = 2
exclude = ['data_pub', ] exclude = ['data_pub', ]
# class EquipamentoPrevistoInline(admin.TabularInline):
class EquipamentoPrevistoInline(admin.TabularInline): # model = EquipamentoPrevisto
model = EquipamentoPrevisto # extra = 2
extra = 2 # raw_id_fields = ('equipamento',)
raw_id_fields = ('equipamento',)
class AnexoAdmin(BaseModelAdmin): class AnexoAdmin(BaseModelAdmin):
date_hierarchy = 'data_pub' date_hierarchy = 'data_pub'
@ -36,14 +34,23 @@ class AnexoAdmin(BaseModelAdmin):
search_fields = ('descricao', 'convenio__id', 'arquivo', search_fields = ('descricao', 'convenio__id', 'arquivo',
'convenio__casa_legislativa__nome') 'convenio__casa_legislativa__nome')
class AcompanhaFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs):
super(AcompanhaFilter, self).__init__(*args, **kwargs)
servidores = Servidor.objects.filter(
convenio__isnull=False).order_by('nome_completo').distinct()
self.lookup_choices = [(x.id, x) for x in servidores]
class ConvenioAdmin(BaseModelAdmin): class ConvenioAdmin(BaseModelAdmin):
change_list_template = 'convenios/change_list.html' change_list_template = 'convenios/change_list.html'
fieldsets = ( fieldsets = (
(None, (None,
{'fields': ('casa_legislativa', 'num_processo_sf', 'num_convenio', {'fields': ('casa_legislativa', 'num_processo_sf', 'num_convenio',
'projeto', 'observacao')} 'projeto', 'data_sigad', 'data_sigi',)}
), ),
(_(u"Acompanhamento no gabinete"),
{'fields': ('status', 'acompanha', 'observacao',)}
),
(_(u'Datas'), (_(u'Datas'),
{'fields': ('data_adesao', 'data_retorno_assinatura', 'duracao', {'fields': ('data_adesao', 'data_retorno_assinatura', 'duracao',
'data_termo_aceite', 'data_pub_diario', 'data_termo_aceite', 'data_pub_diario',
@ -53,15 +60,16 @@ class ConvenioAdmin(BaseModelAdmin):
{'fields': ('data_devolucao_sem_assinatura', 'data_retorno_sem_assinatura',)} {'fields': ('data_devolucao_sem_assinatura', 'data_retorno_sem_assinatura',)}
), ),
) )
readonly_fields = ('data_sigi',)
actions = ['adicionar_convenios'] actions = ['adicionar_convenios']
inlines = (TramitacaoInline, AnexosInline, EquipamentoPrevistoInline) inlines = (AnexosInline,)
list_display = ('num_convenio', 'casa_legislativa', 'get_uf', list_display = ('num_convenio', 'casa_legislativa', 'get_uf',
'status_convenio', 'link_sigad', 'data_adesao', 'status_convenio', 'link_sigad', 'data_retorno_assinatura',
'data_retorno_assinatura', 'duracao', 'data_pub_diario', 'duracao', 'projeto', 'status', 'acompanha',)
'data_termo_aceite', 'projeto',
)
list_display_links = ('num_convenio', 'casa_legislativa',) list_display_links = ('num_convenio', 'casa_legislativa',)
list_filter = ('projeto', 'casa_legislativa__tipo', 'conveniada','equipada', 'casa_legislativa__municipio__uf', ) list_filter = ('status', ('acompanha', AcompanhaFilter), 'projeto',
'casa_legislativa__tipo', 'conveniada','equipada',
'casa_legislativa__municipio__uf',)
#date_hierarchy = 'data_adesao' #date_hierarchy = 'data_adesao'
ordering = ('casa_legislativa__tipo__sigla', 'casa_legislativa__municipio__uf', 'casa_legislativa') ordering = ('casa_legislativa__tipo__sigla', 'casa_legislativa__municipio__uf', 'casa_legislativa')
raw_id_fields = ('casa_legislativa',) raw_id_fields = ('casa_legislativa',)
@ -79,7 +87,7 @@ class ConvenioAdmin(BaseModelAdmin):
return "" return ""
status = obj.get_status() status = obj.get_status()
if status in [u"Vencido", u"Desistência"]: if status in [u"Vencido", u"Desistência", u"Cancelado"]:
label = r"danger" label = r"danger"
elif status == u"Vigente": elif status == u"Vigente":
label = r"success" label = r"success"
@ -101,24 +109,26 @@ class ConvenioAdmin(BaseModelAdmin):
link_sigad.allow_tags = True link_sigad.allow_tags = True
def changelist_view(self, request, extra_context=None): def changelist_view(self, request, extra_context=None):
import re def normaliza_data(nome_param):
import re
if nome_param in request.GET:
value = request.GET.get(nome_param, '')
if value == '':
del request.GET[nome_param]
elif re.match('^\d*$', value): # Year only
# Complete with january 1st
request.GET[nome_param] = "%s-01-01" % value
elif re.match('^\d*\D\d*$', value): # Year and month
# Complete with 1st day of month
request.GET[nome_param] = '%s-01' % value
request.GET._mutable = True request.GET._mutable = True
if 'data_retorno_assinatura__gte' in request.GET: normaliza_data('data_retorno_assinatura__gte')
value = request.GET.get('data_retorno_assinatura__gte', '') normaliza_data('data_retorno_assinatura__lte')
if value == '': normaliza_data('data_sigad__gte')
del request.GET['data_retorno_assinatura__gte'] normaliza_data('data_sigad__lte')
elif re.match('^\d*$', value): # Year only normaliza_data('data_sigi__gte')
request.GET['data_retorno_assinatura__gte'] = "%s-01-01" % value # Complete with january 1st normaliza_data('data_sigi__lte')
elif re.match('^\d*\D\d*$', value): # Year and month
request.GET['data_retorno_assinatura__gte'] = '%s-01' % value # Complete with 1st day of month
if 'data_retorno_assinatura__lte' in request.GET:
value = request.GET.get('data_retorno_assinatura__lte', '')
if value == '':
del request.GET['data_retorno_assinatura__lte']
elif re.match('^\d*$', value): # Year only
request.GET['data_retorno_assinatura__lte'] = "%s-01-01" % value # Complete with january 1st
elif re.match('^\d*\D\d*$', value): # Year and month
request.GET['data_retorno_assinatura__lte'] = '%s-01' % value # Complete with 1st day of month
request.GET._mutable = False request.GET._mutable = False
return super(ConvenioAdmin, self).changelist_view( return super(ConvenioAdmin, self).changelist_view(
@ -169,5 +179,6 @@ class EquipamentoPrevistoAdmin(BaseModelAdmin):
'equipamento__modelo__modelo', 'equipamento__modelo__tipo__tipo') 'equipamento__modelo__modelo', 'equipamento__modelo__tipo__tipo')
admin.site.register(Projeto) admin.site.register(Projeto)
admin.site.register(StatusConvenio)
admin.site.register(Convenio, ConvenioAdmin) admin.site.register(Convenio, ConvenioAdmin)
admin.site.register(EquipamentoPrevisto, EquipamentoPrevistoAdmin) admin.site.register(EquipamentoPrevisto, EquipamentoPrevistoAdmin)

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

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('convenios', '0002_convenio_duracao'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='convenio',
name='casa_legislativa',
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
preserve_default=True,
),
]

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

@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('servidores', '0001_initial'),
('convenios', '0003_auto_20210406_1945'),
]
operations = [
migrations.CreateModel(
name='StatusConvenio',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('nome', models.CharField(max_length=100)),
('cancela', models.BooleanField(default=False, verbose_name='Cancela o conv\xeanio')),
],
options={
'ordering': ('nome',),
'verbose_name': 'Estado de convenios',
'verbose_name_plural': 'Estados de convenios',
},
bases=(models.Model,),
),
migrations.AddField(
model_name='convenio',
name='acompanha',
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='acompanhado por', blank=True, to='servidores.Servidor', null=True),
preserve_default=True,
),
migrations.AddField(
model_name='convenio',
name='status',
field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='estado atual', blank=True, to='convenios.StatusConvenio', null=True),
preserve_default=True,
),
migrations.AlterField(
model_name='convenio',
name='casa_legislativa',
field=models.ForeignKey(verbose_name='\xf3rg\xe3o conveniado', to='casas.Orgao'),
preserve_default=True,
),
migrations.AlterField(
model_name='convenio',
name='data_adesao',
field=models.DateField(null=True, verbose_name='aderidas', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='convenio',
name='data_retorno_assinatura',
field=models.DateField(help_text='Conv\xeanio firmado.', null=True, verbose_name='conveniadas', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='convenio',
name='data_termo_aceite',
field=models.DateField(help_text='Equipamentos recebidos.', null=True, verbose_name='equipadas', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='convenio',
name='duracao',
field=models.PositiveIntegerField(help_text='Deixar em branco caso a dura\xe7\xe3o seja indefinida', null=True, verbose_name='dura\xe7\xe3o (meses)', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='convenio',
name='observacao',
field=models.TextField(null=True, verbose_name='observa\xe7\xf5es', blank=True),
preserve_default=True,
),
]

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

@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('convenios', '0004_auto_20210407_1928'),
]
operations = [
migrations.AddField(
model_name='convenio',
name='data_sigad',
field=models.DateField(null=True, verbose_name='data de cadastro no SIGAD', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='convenio',
name='data_sigi',
field=models.DateField(auto_now_add=True, verbose_name='data de cadastro no SIGI', null=True),
preserve_default=True,
),
]

62
sigi/apps/convenios/models.py

@ -4,6 +4,7 @@ from datetime import datetime, date
from django.db import models from django.db import models
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from sigi.apps.utils import SearchField from sigi.apps.utils import SearchField
from sigi.apps.servidores.models import Servidor
class Projeto(models.Model): class Projeto(models.Model):
@ -17,6 +18,17 @@ class Projeto(models.Model):
def __unicode__(self): def __unicode__(self):
return self.sigla return self.sigla
class StatusConvenio(models.Model):
nome = models.CharField(max_length=100)
cancela = models.BooleanField(_(u"Cancela o convênio"), default=False)
class Meta:
ordering = ('nome',)
verbose_name = _(u"Estado de convenios")
verbose_name_plural = _(u"Estados de convenios")
def __unicode__(self):
return self.nome
class Convenio(models.Model): class Convenio(models.Model):
@ -29,8 +41,8 @@ class Convenio(models.Model):
um pacto de colaboração entre as partes um pacto de colaboração entre as partes
""" """
casa_legislativa = models.ForeignKey( casa_legislativa = models.ForeignKey(
'casas.CasaLegislativa', 'casas.Orgao',
verbose_name=_(u'Casa Legislativa') verbose_name=_(u'órgão conveniado')
) )
# campo de busca em caixa baixa e sem acentos # campo de busca em caixa baixa e sem acentos
search_text = SearchField(field_names=['casa_legislativa']) search_text = SearchField(field_names=['casa_legislativa'])
@ -47,19 +59,49 @@ class Convenio(models.Model):
max_length=10, max_length=10,
blank=True blank=True
) )
status = models.ForeignKey(
StatusConvenio,
on_delete=models.SET_NULL,
verbose_name=_(u"estado atual"),
null=True,
blank=True
)
data_sigad = models.DateField(
_(u"data de cadastro no SIGAD"),
null=True,
blank=True
)
data_sigi = models.DateField(
_(u"data de cadastro no SIGI"),
blank=True,
null=True,
auto_now_add=True
)
acompanha = models.ForeignKey(
Servidor,
on_delete=models.SET_NULL,
verbose_name=_(u"acompanhado por"),
null=True,
blank=True
)
observacao = models.TextField(
_(u"observações"),
null=True,
blank=True,
)
data_adesao = models.DateField( data_adesao = models.DateField(
_(u'Aderidas'), _(u'aderidas'),
null=True, null=True,
blank=True, blank=True,
) )
data_retorno_assinatura = models.DateField( data_retorno_assinatura = models.DateField(
_(u'Conveniadas'), _(u'conveniadas'),
null=True, null=True,
blank=True, blank=True,
help_text=_(u'Convênio firmado.') help_text=_(u'Convênio firmado.')
) )
duracao = models.PositiveIntegerField( duracao = models.PositiveIntegerField(
_(u"Duração (meses)"), _(u"duração (meses)"),
null=True, null=True,
blank=True, blank=True,
help_text=_(u"Deixar em branco caso a duração seja indefinida") help_text=_(u"Deixar em branco caso a duração seja indefinida")
@ -70,7 +112,7 @@ class Convenio(models.Model):
blank=True blank=True
) )
data_termo_aceite = models.DateField( data_termo_aceite = models.DateField(
_(u'Equipadas'), _(u'equipadas'),
null=True, null=True,
blank=True, blank=True,
help_text=_(u'Equipamentos recebidos.') help_text=_(u'Equipamentos recebidos.')
@ -98,11 +140,6 @@ class Convenio(models.Model):
blank=True, blank=True,
help_text=_(u'Data do retorno do convênio sem assinatura'), help_text=_(u'Data do retorno do convênio sem assinatura'),
) )
observacao = models.CharField(
null=True,
blank=True,
max_length=100,
)
conveniada = models.BooleanField(default=False) conveniada = models.BooleanField(default=False)
equipada = models.BooleanField(default=False) equipada = models.BooleanField(default=False)
@ -128,6 +165,9 @@ class Convenio(models.Model):
return data_fim return data_fim
def get_status(self): def get_status(self):
if self.status and self.status.cancela:
return _(u"Cancelado")
if self.data_retorno_assinatura is not None: if self.data_retorno_assinatura is not None:
if self.duracao is not None: if self.duracao is not None:
if date.today() >= self.get_termino_convenio(): if date.today() >= self.get_termino_convenio():

68
sigi/apps/convenios/templates/convenios/change_list.html

@ -1,19 +1,61 @@
{% extends "change_list_with_cart.html" %} {% extends "change_list_with_cart.html" %}
{% load i18n %} {% load i18n %}
{% block search %} {% block extra_search %}
<div id="toolbar"> <nav class="navbar navbar-default">
<form id="changelist-search" action="" method="get"> <div class="container-fluid">
<div><!-- DIV needed for valid HTML --> <div class="navbar-header">
<label for="searchbar"><img src="/static/admin/img/icon_searchbox.png" alt="Search" /></label> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<input type="text" size="40" name="q" value="" id="searchbar" /> <span class="sr-only">Toggle navigation</span>
<label for="data_retorno_assinatura__gte">{% trans 'Conveniadas a partir de' %}:</label> <span class="icon-bar"></span>
<input type="text" size="10" name="data_retorno_assinatura__gte" value="" id="data_retorno_assinatura__gte" class="vDateField"/> <span class="icon-bar"></span>
<label for="data_retorno_assinatura__lte">{% trans 'até' %}:</label> <span class="icon-bar"></span>
<input type="text" size="10" name="data_retorno_assinatura__lte" value="" id="data_retorno_assinatura__lte" /> </button>
<input type="submit" value="Pesquisar" /> <a class="navbar-brand" href="#">Filtro de datas</a>
{% trans 'Datas podem ser: Um ano (aaaa), um mês (aaaa-mm) ou um dia (aaaa-mm-dd)' %} <p class="navbar-text">Use AAAA, AAAA-MM ou AAAA-MM-DD</p>
</div> </div>
</form> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-left" role="extra-search" id="changelist-extrasearch" action="" method="get">
<div class="form-group">
<label for="data_retorno_assinatura__gte">{% trans 'Conveniadas a partir de' %}:</label>
<input type="text" class="form-control search-query" size="10" name="data_retorno_assinatura__gte" value="" id="data_retorno_assinatura__gte">
<label for="data_retorno_assinatura__lte">{% trans 'até' %}:</label>
<input type="text" class="form-control search-query" size="10" name="data_retorno_assinatura__lte" value="" id="data_retorno_assinatura__lte">
</div>
<div class="form-group">
<label for="data_sigad__gte">{% trans 'SIGAD a partir de' %}:</label>
<input type="text" class="form-control search-query" size="10" name="data_sigad__gte" value="" id="data_sigad__gte">
<label for="data_sigad__lte">{% trans 'até' %}:</label>
<input type="text" class="form-control search-query" size="10" name="data_sigad__lte" value="" id="data_sigad__lte">
</div>
<div class="form-group">
<label for="data_sigi__gte">{% trans 'SIGI a partir de' %}:</label>
<input type="text" class="form-control search-query" size="10" name="data_sigi__gte" value="" id="data_sigi__gte">
<label for="data_sigi__lte">{% trans 'até' %}:</label>
<input type="text" class="form-control search-query" size="10" name="data_sigi__lte" value="" id="data_sigi__lte">
</div>
<button type="submit" class="btn btn-default navbar-btn ">
<span class="glyphicon glyphicon-search"></span>
</button>
</form>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
{% comment %}
<form class="navbar-form navbar-right" role="extra-search" id="changelist-extrasearch" action="" method="get">
<div class="form-group"><!-- DIV needed for valid HTML -->
<div class="input-group">
<label for="data_retorno_assinatura__gte">{% trans 'Conveniadas a partir de' %}:</label>
<input type="text" class="form-control search-query" placeholder="YYYY ou YYYY-MM ou YYYY-MM-DD" size="10" name="data_retorno_assinatura__gte" value="" id="data_retorno_assinatura__gte">
<label for="data_retorno_assinatura__lte">{% trans 'até' %}:</label>
<input type="text" class="form-control search-query" placeholder="YYYY ou YYYY-MM ou YYYY-MM-DD" size="10" name="data_retorno_assinatura__lte" value="" id="data_retorno_assinatura__lte">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div> </div>
</form>
{% endcomment %}
{% endblock %} {% endblock %}

4
sigi/apps/convenios/views.py

@ -11,7 +11,7 @@ from django.template import Context, loader
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from geraldo.generators import PDFGenerator from geraldo.generators import PDFGenerator
from sigi.apps.casas.models import CasaLegislativa 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, Projeto from sigi.apps.convenios.models import Convenio, Projeto
from sigi.apps.convenios.reports import ConvenioPorCMReport, ConvenioPorALReport, ConvenioReportSemAceiteAL, ConvenioReportSemAceiteCM from sigi.apps.convenios.reports import ConvenioPorCMReport, ConvenioPorALReport, ConvenioReportSemAceiteAL, ConvenioReportSemAceiteCM
@ -249,7 +249,7 @@ def report_regiao(request, regiao='NE'):
projetos = Projeto.objects.all() projetos = Projeto.objects.all()
camaras = CasaLegislativa.objects.filter(tipo__sigla='CM') camaras = Orgao.objects.filter(tipo__sigla='CM')
tabelas = list() tabelas = list()
# Geral # Geral

10
sigi/apps/diagnosticos/forms.py

@ -11,7 +11,7 @@ from django.utils.translation import ugettext as _
from eav.fields import RangeField from eav.fields import RangeField
from eav.forms import BaseDynamicEntityForm from eav.forms import BaseDynamicEntityForm
from sigi.apps.casas.models import CasaLegislativa, 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
@ -132,23 +132,23 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
self.initial[schema.name] = value self.initial[schema.name] = value
class CasaLegislativaMobileForm(forms.ModelForm): class OrgaoMobileForm(forms.ModelForm):
data_instalacao = forms.DateField(label=_(u'Data de instalação da Casa Legislativa'), required=False) data_instalacao = forms.DateField(label=_(u'Data de instalação da Casa Legislativa'), required=False)
data_criacao = forms.DateField() data_criacao = forms.DateField()
class Meta: class Meta:
model = CasaLegislativa 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(CasaLegislativaMobileForm, self).__init__(*args, **kwargs) super(OrgaoMobileForm, self).__init__(*args, **kwargs)
self.fields['data_criacao'] = forms.DateField( self.fields['data_criacao'] = forms.DateField(
label=_(u'Data de criação do Município'), label=_(u'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(CasaLegislativaMobileForm, 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()

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

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('diagnosticos', '0003_auto_20201101_2240'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='diagnostico',
name='casa_legislativa',
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
preserve_default=True,
),
]

2
sigi/apps/diagnosticos/models.py

@ -14,7 +14,7 @@ class Diagnostico(BaseEntity):
em uma Casa Legislativa em uma Casa Legislativa
""" """
casa_legislativa = models.ForeignKey( casa_legislativa = models.ForeignKey(
'casas.CasaLegislativa', 'casas.Orgao',
verbose_name=_(u'Casa Legislativa')) verbose_name=_(u'Casa Legislativa'))
# campo de busca em caixa baixa e sem acento # campo de busca em caixa baixa e sem acento

6
sigi/apps/diagnosticos/views.py

@ -12,7 +12,7 @@ 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 (DiagnosticoMobileForm,
CasaLegislativaMobileForm, FuncionariosMobileForm) 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
@ -117,7 +117,7 @@ def categoria_casa_legislativa(request, id_diagnostico):
casa_legislativa = diagnostico.casa_legislativa casa_legislativa = diagnostico.casa_legislativa
if request.method == "POST": if request.method == "POST":
form = CasaLegislativaMobileForm(request.POST, form = OrgaoMobileForm(request.POST,
instance=casa_legislativa) instance=casa_legislativa)
if form.is_valid(): if form.is_valid():
form.save() form.save()
@ -133,7 +133,7 @@ def categoria_casa_legislativa(request, id_diagnostico):
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 = CasaLegislativaMobileForm(instance=casa_legislativa) form = OrgaoMobileForm(instance=casa_legislativa)
context = RequestContext(request, {'form': form, context = RequestContext(request, {'form': form,
'diagnostico': diagnostico, 'casa_legislativa': casa_legislativa}) 'diagnostico': diagnostico, 'casa_legislativa': casa_legislativa})

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

@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('eventos', '0004_remove_evento_curso_moodle_id'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='convite',
name='casa',
field=models.ForeignKey(verbose_name='Casa convidada', to='casas.Orgao'),
preserve_default=True,
),
migrations.AlterField(
model_name='evento',
name='casa_anfitria',
field=models.ForeignKey(verbose_name='Casa anfitri\xe3', blank=True, to='casas.Orgao', null=True),
preserve_default=True,
),
]

6
sigi/apps/eventos/models.py

@ -3,7 +3,7 @@
from django.db import models from django.db import models
from django.utils.functional import lazy from django.utils.functional import lazy
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.contatos.models import Municipio from sigi.apps.contatos.models import Municipio
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
@ -33,7 +33,7 @@ class Evento(models.Model):
solicitante = models.CharField(_(u"Solicitante"), max_length=100) solicitante = models.CharField(_(u"Solicitante"), max_length=100)
data_inicio = models.DateField(_(u"Data de início")) data_inicio = models.DateField(_(u"Data de início"))
data_termino = models.DateField(_(u"Data de término")) data_termino = models.DateField(_(u"Data de término"))
casa_anfitria = models.ForeignKey(CasaLegislativa, verbose_name=_(u"Casa anfitriã"), blank=True, casa_anfitria = models.ForeignKey(Orgao, verbose_name=_(u"Casa anfitriã"), blank=True,
null=True) null=True)
municipio = models.ForeignKey(Municipio) municipio = models.ForeignKey(Municipio)
local = models.TextField(_(u"Local do evento"), blank=True) local = models.TextField(_(u"Local do evento"), blank=True)
@ -87,7 +87,7 @@ class Equipe(models.Model):
class Convite(models.Model): class Convite(models.Model):
evento = models.ForeignKey(Evento) evento = models.ForeignKey(Evento)
casa = models.ForeignKey(CasaLegislativa, verbose_name=_(u"Casa convidada")) casa = models.ForeignKey(Orgao, verbose_name=_(u"Casa convidada"))
servidor = models.ForeignKey(Servidor, verbose_name=_(u"Servidor que convidou")) servidor = models.ForeignKey(Servidor, verbose_name=_(u"Servidor que convidou"))
data_convite = models.DateField(_(u"Data do convite")) data_convite = models.DateField(_(u"Data do convite"))
aceite = models.BooleanField(_("Aceitou o convite"), default=False) aceite = models.BooleanField(_("Aceitou o convite"), default=False)

16
sigi/apps/home/templatetags/menu_conf.yaml

@ -8,15 +8,17 @@ main_menu:
url: contatos/unidadefederativa/ url: contatos/unidadefederativa/
- title: Mesorregiões - title: Mesorregiões
url: contatos/mesorregiao/ url: contatos/mesorregiao/
- title: Casas Legislativas - title: Casas e órgãos
url: casas/casalegislativa/ url: casas/orgao/
children: children:
- title: Todas - title: Todo legislativo
url: casas/casalegislativa/ url: casas/orgao/?tipo__legislativo__exact=1
- title: Câmaras Municipais - title: Câmaras Municipais
url: casas/casalegislativa/?tipo__id__exact=1 url: casas/orgao/?tipo__sigla__exact=CM
- title: Assembléias Legislativas - title: Assembléias Legislativas
url: casas/casalegislativa/?tipo__id__exact=2 url: casas/orgao/?tipo__sigla__exact=AL
- title: Demais órgãos
url: casas/orgao/?tipo__legislativo__exact=0
- title: Organizar relacionamentos - title: Organizar relacionamentos
url: casas/portfolio/ url: casas/portfolio/
- title: Carteira de relacionamentos - title: Carteira de relacionamentos
@ -50,6 +52,8 @@ main_menu:
url: convenios/convenio/ url: convenios/convenio/
- title: Planos diretores - title: Planos diretores
url: metas/planodiretor/ url: metas/planodiretor/
- title: Tabela de acompanhamento
url: convenios/statusconvenio/
# - title: Inventário # - title: Inventário
# url: inventario/bem/ # url: inventario/bem/
# children: # children:

14
sigi/apps/home/views.py

@ -27,7 +27,7 @@ import calendar
from django.shortcuts import render, get_object_or_404 from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from itertools import cycle from itertools import cycle
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.convenios.models import Convenio, Projeto from sigi.apps.convenios.models import Convenio, Projeto
from sigi.apps.diagnosticos.models import Diagnostico from sigi.apps.diagnosticos.models import Diagnostico
from sigi.apps.metas.models import Meta from sigi.apps.metas.models import Meta
@ -128,7 +128,7 @@ def chart_carteira(request):
'highlight': highlights.next(), 'highlight': highlights.next(),
'label': r['gerentes_interlegis__nome_completo'] 'label': r['gerentes_interlegis__nome_completo']
} }
for r in CasaLegislativa.objects.exclude( for r in Orgao.objects.exclude(
gerentes_interlegis=None).values( gerentes_interlegis=None).values(
'gerentes_interlegis__nome_completo').annotate( 'gerentes_interlegis__nome_completo').annotate(
total_casas=Count('pk')).order_by( total_casas=Count('pk')).order_by(
@ -144,7 +144,7 @@ def chart_performance(request):
servidor = request.GET.get('servidor', None) servidor = request.GET.get('servidor', None)
if servidor is None: if servidor is None:
casas = CasaLegislativa.objects.exclude(gerentes_interlegis=None) casas = Orgao.objects.exclude(gerentes_interlegis=None)
else: else:
gerente = get_object_or_404(Servidor, pk=servidor) gerente = get_object_or_404(Servidor, pk=servidor)
casas = gerente.casas_que_gerencia casas = gerente.casas_que_gerencia
@ -228,7 +228,7 @@ def busca_informacoes_camara():
Busca informacoes no banco para montar tabela de resumo de camaras por projeto Busca informacoes no banco para montar tabela de resumo de camaras por projeto
Retorna um dicionario de listas Retorna um dicionario de listas
""" """
camaras = CasaLegislativa.objects.filter(tipo__sigla='CM') camaras = Orgao.objects.filter(tipo__sigla='CM')
convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM') convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM')
projetos = Projeto.objects.all() projetos = Projeto.objects.all()
@ -309,10 +309,10 @@ def busca_informacoes_camara():
def sem_convenio(): def sem_convenio():
total = CasaLegislativa.objects.exclude(servico=None).filter(servico__data_desativacao=None, convenio=None).order_by('municipio__uf__sigla', 'nome').distinct('municipio__uf__sigla', 'nome') total = Orgao.objects.exclude(servico=None).filter(servico__data_desativacao=None, convenio=None).order_by('municipio__uf__sigla', 'nome').distinct('municipio__uf__sigla', 'nome')
hospedagem = CasaLegislativa.objects.exclude(servico=None).filter(servico__data_desativacao=None, servico__tipo_servico__modo='H', convenio=None).order_by('municipio__uf__sigla', 'nome').distinct('municipio__uf__sigla', 'nome') hospedagem = Orgao.objects.exclude(servico=None).filter(servico__data_desativacao=None, servico__tipo_servico__modo='H', convenio=None).order_by('municipio__uf__sigla', 'nome').distinct('municipio__uf__sigla', 'nome')
reg_keys = set(total.values_list('pk', flat=True)).difference(set(hospedagem.values_list('pk', flat=True))) reg_keys = set(total.values_list('pk', flat=True)).difference(set(hospedagem.values_list('pk', flat=True)))
registro = CasaLegislativa.objects.filter(pk__in=reg_keys).order_by('municipio__uf__sigla', 'nome') registro = Orgao.objects.filter(pk__in=reg_keys).order_by('municipio__uf__sigla', 'nome')
return { return {
'total': total, 'total': total,
'hospedagem': hospedagem, 'hospedagem': hospedagem,

21
sigi/apps/inventario/migrations/0002_auto_20210406_1945.py

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('inventario', '0001_initial'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='bem',
name='casa_legislativa',
field=models.ForeignKey(to='casas.Orgao'),
preserve_default=True,
),
]

2
sigi/apps/inventario/models.py

@ -72,7 +72,7 @@ class Equipamento(models.Model):
class Bem(models.Model): class Bem(models.Model):
casa_legislativa = models.ForeignKey('casas.CasaLegislativa') casa_legislativa = models.ForeignKey('casas.Orgao')
equipamento = models.ForeignKey(Equipamento) equipamento = models.ForeignKey(Equipamento)
fornecedor = models.ForeignKey(Fornecedor) fornecedor = models.ForeignKey(Fornecedor)
num_serie = models.CharField( num_serie = models.CharField(

21
sigi/apps/metas/migrations/0002_auto_20210406_1945.py

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('metas', '0001_initial'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='planodiretor',
name='casa_legislativa',
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
preserve_default=True,
),
]

4
sigi/apps/metas/models.py

@ -3,7 +3,7 @@ from datetime import date
from django.db import models from django.db import models
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.convenios.models import Projeto, Convenio from sigi.apps.convenios.models import Projeto, Convenio
from sigi.apps.diagnosticos.models import Diagnostico from sigi.apps.diagnosticos.models import Diagnostico
from sigi.apps.financeiro.models import Desembolso from sigi.apps.financeiro.models import Desembolso
@ -115,7 +115,7 @@ class PlanoDiretor(models.Model):
('I', _(u'Implantado')), ('I', _(u'Implantado')),
) )
projeto = models.ForeignKey(Projeto, verbose_name=_(u'Projeto')) projeto = models.ForeignKey(Projeto, verbose_name=_(u'Projeto'))
casa_legislativa = models.ForeignKey(CasaLegislativa, verbose_name=_(u'Casa Legislativa')) casa_legislativa = models.ForeignKey(Orgao, verbose_name=_(u'Casa Legislativa'))
casa_legislativa.casa_uf_filter = True casa_legislativa.casa_uf_filter = True
status = models.CharField(_(u'Status'), max_length=1, choices=STATUS_CHOICE, default='E') status = models.CharField(_(u'Status'), max_length=1, choices=STATUS_CHOICE, default='E')
data_entrega = models.DateField(_(u'Data de entrega'), blank=True, null=True) data_entrega = models.DateField(_(u'Data de entrega'), blank=True, null=True)

4
sigi/apps/metas/templatetags/mapa_tags.py

@ -2,7 +2,7 @@
from django import template from django import template
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.metas.views import parliament_summary from sigi.apps.metas.views import parliament_summary
@ -11,7 +11,7 @@ register = template.Library()
@register.filter(name='map_desc_serv') @register.filter(name='map_desc_serv')
def descricao_servicos(casa): def descricao_servicos(casa):
if not isinstance(casa, CasaLegislativa): if not isinstance(casa, Orgao):
return "" return ""
summary = parliament_summary(casa) summary = parliament_summary(casa)

10
sigi/apps/metas/views.py

@ -17,7 +17,7 @@ from django.utils.translation import ugettext as _
from django.views.decorators.cache import cache_page from django.views.decorators.cache import cache_page
from easy_thumbnails.templatetags.thumbnail import thumbnail_url from easy_thumbnails.templatetags.thumbnail import thumbnail_url
from sigi.apps.casas.models import CasaLegislativa 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 Projeto from sigi.apps.convenios.models import Projeto
from sigi.apps.financeiro.models import Desembolso from sigi.apps.financeiro.models import Desembolso
@ -128,9 +128,9 @@ def map_search(request):
q = request.GET.get('q') q = request.GET.get('q')
if len(q.split(',')) > 1: if len(q.split(',')) > 1:
municipio, uf = [s.strip() for s in q.split(',')] municipio, uf = [s.strip() for s in q.split(',')]
casas = CasaLegislativa.objects.filter(search_text__icontains=to_ascii(municipio), municipio__uf__sigla__iexact=uf) casas = Orgao.objects.filter(search_text__icontains=to_ascii(municipio), municipio__uf__sigla__iexact=uf)
else: else:
casas = CasaLegislativa.objects.filter(search_text__icontains=to_ascii(q)) casas = Orgao.objects.filter(search_text__icontains=to_ascii(q))
if casas.count() > 0: if casas.count() > 0:
response = {'result': 'FOUND', 'ids': [c.pk for c in casas]} response = {'result': 'FOUND', 'ids': [c.pk for c in casas]}
@ -301,7 +301,7 @@ def filtrar_casas(seit, convenios, equipadas, regioes, estados, diagnosticos,
else: else:
qDiagnostico = Q() qDiagnostico = Q()
casas = CasaLegislativa.objects.filter(qRegiao | qEstado).filter(qGerente) casas = Orgao.objects.filter(qRegiao | qEstado).filter(qGerente)
if seit or convenios or equipadas or diagnosticos: if seit or convenios or equipadas or diagnosticos:
casas = casas.filter(qServico | qConvenio | qEquipada | qDiagnostico) casas = casas.filter(qServico | qConvenio | qEquipada | qDiagnostico)
@ -323,7 +323,7 @@ def gera_map_data_file(cronjob=False):
casas = {} casas = {}
for c in CasaLegislativa.objects.prefetch_related('servico_set', 'convenio_set', 'diagnostico_set').all().distinct(): for c in Orgao.objects.prefetch_related('servico_set', 'convenio_set', 'diagnostico_set').all().distinct():
# if c.servico_set.count() == 0 and c.convenio_set.count() == 0 and c.diagnostico_set.count() == 0: # if c.servico_set.count() == 0 and c.convenio_set.count() == 0 and c.diagnostico_set.count() == 0:
# continue # continue
# # Salta essa casa, pois ela não tem nada com o Interlegis # # Salta essa casa, pois ela não tem nada com o Interlegis

21
sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py

@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ocorrencias', '0002_auto_20160308_0828'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='ocorrencia',
name='casa_legislativa',
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
preserve_default=True,
),
]

2
sigi/apps/ocorrencias/models.py

@ -51,7 +51,7 @@ class Ocorrencia(models.Model):
(5, _(u'Baixíssimo')), (5, _(u'Baixíssimo')),
) )
casa_legislativa = models.ForeignKey('casas.CasaLegislativa', verbose_name=_(u'Casa Legislativa')) casa_legislativa = models.ForeignKey('casas.Orgao', verbose_name=_(u'Casa Legislativa'))
casa_legislativa.convenio_uf_filter = True casa_legislativa.convenio_uf_filter = True
casa_legislativa.convenio_cl_tipo_filter = True casa_legislativa.convenio_cl_tipo_filter = True
data_criacao = models.DateField(_(u'Data de criação'), null=True, blank=True, auto_now_add=True) data_criacao = models.DateField(_(u'Data de criação'), null=True, blank=True, auto_now_add=True)

8
sigi/apps/ocorrencias/views.py

@ -8,7 +8,7 @@ from django.views.decorators.http import require_POST
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.template import RequestContext from django.template import RequestContext
from sigi.apps.utils import to_ascii from sigi.apps.utils import to_ascii
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.contatos.models import UnidadeFederativa from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.servidores.models import Servidor, Servico from sigi.apps.servidores.models import Servidor, Servico
from sigi.apps.ocorrencias.models import Ocorrencia, Anexo from sigi.apps.ocorrencias.models import Ocorrencia, Anexo
@ -32,7 +32,7 @@ def painel_ocorrencias(request):
raise Http404("id não definido") raise Http404("id não definido")
if tipo == 'casa': if tipo == 'casa':
casa = get_object_or_404(CasaLegislativa, pk=id) casa = get_object_or_404(Orgao, pk=id)
ocorrencias = casa.ocorrencia_set.all() ocorrencias = casa.ocorrencia_set.all()
panel_title = u"{casa}, {uf}".format( panel_title = u"{casa}, {uf}".format(
casa=casa.nome, casa=casa.nome,
@ -46,7 +46,7 @@ def painel_ocorrencias(request):
'timeline': u"Comentados por mim"} 'timeline': u"Comentados por mim"}
if painel is None: if painel is None:
if CasaLegislativa.objects.filter( if Orgao.objects.filter(
gerentes_interlegis=servidor).count() > 0: gerentes_interlegis=servidor).count() > 0:
painel = 'gerente' painel = 'gerente'
elif Ocorrencia.objects.filter( elif Ocorrencia.objects.filter(
@ -108,7 +108,7 @@ def busca_nominal(request, origin="tudo"):
data = [] data = []
if origin == "casa" or origin == "tudo": if origin == "casa" or origin == "tudo":
casas = CasaLegislativa.objects.filter(search_text__icontains=to_ascii(term)).select_related('municipio', 'municipio__uf')[:10] casas = Orgao.objects.filter(search_text__icontains=to_ascii(term)).select_related('municipio', 'municipio__uf')[:10]
data += [{'value': c.pk, 'label': "%s, %s" % (c.nome, c.municipio.uf.sigla,), 'origin': 'casa'} for c in casas] data += [{'value': c.pk, 'label': "%s, %s" % (c.nome, c.municipio.uf.sigla,), 'origin': 'casa'} for c in casas]
if origin == "servidor" or origin == "tudo": if origin == "servidor" or origin == "tudo":

27
sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py

@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('parlamentares', '0001_initial'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='legislatura',
name='casa_legislativa',
field=models.ForeignKey(to='casas.Orgao'),
preserve_default=True,
),
migrations.AlterField(
model_name='mesadiretora',
name='casa_legislativa',
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
preserve_default=True,
),
]

6
sigi/apps/parlamentares/models.py

@ -2,7 +2,7 @@
from django.db import models from django.db import models
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
class Partido(models.Model): class Partido(models.Model):
@ -82,7 +82,7 @@ class Mandato(models.Model):
class Legislatura(models.Model): class Legislatura(models.Model):
casa_legislativa = models.ForeignKey(CasaLegislativa) casa_legislativa = models.ForeignKey(Orgao)
numero = models.PositiveSmallIntegerField(_(u'número legislatura')) numero = models.PositiveSmallIntegerField(_(u'número legislatura'))
data_inicio = models.DateField(_(u'início')) data_inicio = models.DateField(_(u'início'))
data_fim = models.DateField(_(u'fim')) data_fim = models.DateField(_(u'fim'))
@ -174,7 +174,7 @@ class SessaoLegislativa(models.Model):
class MesaDiretora(models.Model): class MesaDiretora(models.Model):
casa_legislativa = models.ForeignKey( casa_legislativa = models.ForeignKey(
'casas.CasaLegislativa', 'casas.Orgao',
verbose_name=_(u'Casa Legislativa') verbose_name=_(u'Casa Legislativa')
) )

4
sigi/apps/parlamentares/reports.py

@ -47,7 +47,7 @@ class ParlamentaresLabels(Report):
Usage example:: Usage example::
>>> from geraldo.generators import PDFGenerator >>> from geraldo.generators import PDFGenerator
>>> queryset = CasaLegislativa.objects.filter(municipio__uf__sigla='MG') >>> queryset = Orgao.objects.filter(municipio__uf__sigla='MG')
>>> report = LabelsReport(queryset) >>> report = LabelsReport(queryset)
>>> report.generate_by(PDFGenerator, filename='./inline-detail-report.pdf') >>> report.generate_by(PDFGenerator, filename='./inline-detail-report.pdf')
@ -268,7 +268,7 @@ def label_text(text):
return "%s: " % text return "%s: " % text
class InfoCasaLegislativa(ReportDefault): class InfoOrgao(ReportDefault):
title = _(u'Casa Legislativa') title = _(u'Casa Legislativa')
class band_summary(ReportBand): class band_summary(ReportBand):

2
sigi/apps/parlamentares/views.py

@ -10,7 +10,7 @@ from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext from django.template import RequestContext
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.parlamentares.models import Parlamentar from sigi.apps.parlamentares.models import Parlamentar
from sigi.apps.parlamentares.reports import ParlamentaresLabels from sigi.apps.parlamentares.reports import ParlamentaresLabels

9
sigi/apps/servicos/admin.py

@ -7,8 +7,9 @@ from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from sigi.apps.casas.admin import FuncionariosInline from sigi.apps.casas.admin import FuncionariosInline
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.servicos.models import Servico, LogServico, CasaAtendida, TipoServico from sigi.apps.servicos.models import (Servico, LogServico, CasaAtendida,
TipoServico)
from sigi.apps.utils.base_admin import BaseModelAdmin from sigi.apps.utils.base_admin import BaseModelAdmin
@ -163,7 +164,7 @@ class ServicoAdmin(BaseModelAdmin):
if not id_casa: if not id_casa:
raise Http404 raise Http404
obj.casa_legislativa = CasaAtendida.objects.get(pk=id_casa) obj.casa_legislativa = Orgao.objects.get(pk=id_casa)
return obj return obj
@ -210,7 +211,7 @@ class CasaAtendidaAdmin(BaseModelAdmin):
def change_view(self, request, object_id, extra_context=None): def change_view(self, request, object_id, extra_context=None):
# Se a Casa ainda não é atendida, gerar o código interlegis para ela # Se a Casa ainda não é atendida, gerar o código interlegis para ela
# Assim ela passa a ser uma casa atendida # Assim ela passa a ser uma casa atendida
casa = CasaLegislativa.objects.get(id=object_id) casa = Orgao.objects.get(id=object_id)
if casa.codigo_interlegis == '': if casa.codigo_interlegis == '':
casa.gerarCodigoInterlegis() casa.gerarCodigoInterlegis()

17
sigi/apps/servicos/migrations/0004_delete_casaatendida.py

@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('servicos', '0003_auto_20170407_1003'),
]
operations = [
migrations.DeleteModel(
name='CasaAtendida',
),
]

27
sigi/apps/servicos/migrations/0005_auto_20210406_1945.py

@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('servicos', '0004_delete_casaatendida'),
('casas', '0014_auto_20210406_1945'),
]
operations = [
migrations.AlterField(
model_name='casamanifesta',
name='casa_legislativa',
field=models.OneToOneField(to='casas.Orgao'),
preserve_default=True,
),
migrations.AlterField(
model_name='servico',
name='casa_legislativa',
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'),
preserve_default=True,
),
]

25
sigi/apps/servicos/migrations/0006_casaatendida.py

@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('casas', '0014_auto_20210406_1945'),
('servicos', '0005_auto_20210406_1945'),
]
operations = [
migrations.CreateModel(
name='CasaAtendida',
fields=[
],
options={
'proxy': True,
'verbose_name_plural': 'Casas atendidas',
},
bases=('casas.orgao',),
),
]

8
sigi/apps/servicos/models.py

@ -2,7 +2,7 @@
from datetime import date from datetime import date
from django.db import models from django.db import models
from sigi.apps.casas.models import CasaLegislativa, Funcionario from sigi.apps.casas.models import Orgao, Funcionario
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
@ -37,7 +37,7 @@ class TipoServico(models.Model):
class Servico(models.Model): class Servico(models.Model):
casa_legislativa = models.ForeignKey(CasaLegislativa, verbose_name=_(u'Casa Legislativa')) casa_legislativa = models.ForeignKey(Orgao, verbose_name=_(u'Casa Legislativa'))
tipo_servico = models.ForeignKey(TipoServico, verbose_name=_(u'Tipo de serviço')) tipo_servico = models.ForeignKey(TipoServico, verbose_name=_(u'Tipo de serviço'))
contato_tecnico = models.ForeignKey(Funcionario, verbose_name=_(u'Contato técnico'), related_name='contato_tecnico', on_delete=models.PROTECT) contato_tecnico = models.ForeignKey(Funcionario, verbose_name=_(u'Contato técnico'), related_name='contato_tecnico', on_delete=models.PROTECT)
contato_administrativo = models.ForeignKey(Funcionario, verbose_name=_(u'Contato administrativo'), related_name='contato_administrativo', on_delete=models.PROTECT) contato_administrativo = models.ForeignKey(Funcionario, verbose_name=_(u'Contato administrativo'), related_name='contato_administrativo', on_delete=models.PROTECT)
@ -183,7 +183,7 @@ class CasaAtendidaManager(models.Manager):
return qs return qs
class CasaAtendida(CasaLegislativa): class CasaAtendida(Orgao):
class Meta: class Meta:
proxy = True proxy = True
@ -193,7 +193,7 @@ class CasaAtendida(CasaLegislativa):
class CasaManifesta(models.Model): class CasaManifesta(models.Model):
casa_legislativa = models.OneToOneField(CasaLegislativa) casa_legislativa = models.OneToOneField(Orgao)
data_manifestacao = models.DateTimeField(auto_now_add=True) data_manifestacao = models.DateTimeField(auto_now_add=True)
data_atualizacao = models.DateTimeField(auto_now=True) data_atualizacao = models.DateTimeField(auto_now=True)
informante = models.CharField(_(u'Nome do informante'), max_length=100, blank=True) informante = models.CharField(_(u'Nome do informante'), max_length=100, blank=True)

2
sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html

@ -15,7 +15,7 @@ function dismissRelatedLookupPopup(win, chosenId) {
{% block object-tools-items %} {% block object-tools-items %}
<li><a id="lookup_id_casa_legislativa" onclick="return showRelatedObjectLookupPopup(this);" <li><a id="lookup_id_casa_legislativa" onclick="return showRelatedObjectLookupPopup(this);"
href="{% url 'admin:casas_casalegislativa_changelist' %}?codigo_interlegis__exact=" class="addlink"> href="{% url 'admin:casas_orgao_changelist' %}?codigo_interlegis__exact=" class="addlink">
<span class="glyphicon glyphicon-plus"></span> <span class="glyphicon glyphicon-plus"></span>
{% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %} {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
</a></li> </a></li>

9
sigi/apps/servicos/views.py

@ -10,9 +10,10 @@ from django.template.context import RequestContext
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.views.generic.base import TemplateView from django.views.generic.base import TemplateView
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import Orgao
from sigi.apps.contatos.models import UnidadeFederativa from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.servicos.models import TipoServico, CasaAtendida, CasaManifesta, ServicoManifesto from sigi.apps.servicos.models import (TipoServico, CasaManifesta, CasaAtendida,
ServicoManifesto)
class MapaView(TemplateView): class MapaView(TemplateView):
@ -75,7 +76,7 @@ class CasaManifestaProtoForm(forms.Form):
def casa_manifesta_view(request): def casa_manifesta_view(request):
if 'casa_id' in request.GET: if 'casa_id' in request.GET:
casa_id = request.GET.get('casa_id') casa_id = request.GET.get('casa_id')
casa = get_object_or_404(CasaLegislativa, pk=casa_id) casa = get_object_or_404(Orgao, pk=casa_id)
# Criar um formulário dinâmico # Criar um formulário dinâmico
@ -138,7 +139,7 @@ def casa_manifesta_view(request):
extra_context = {'casa': casa, 'cmf': cmf} extra_context = {'casa': casa, 'cmf': cmf}
elif 'uf' in request.GET: elif 'uf' in request.GET:
uf = request.GET.get('uf') uf = request.GET.get('uf')
extra_context = {'casa_list': CasaLegislativa.objects.filter(municipio__uf__sigla=uf)} extra_context = {'casa_list': Orgao.objects.filter(municipio__uf__sigla=uf)}
else: else:
extra_context = {'uf_list': UnidadeFederativa.objects.all()} extra_context = {'uf_list': UnidadeFederativa.objects.all()}

6
sigi/test_cart.py

@ -8,7 +8,7 @@ from sigi.testutils import pdf_text
@pytest.mark.parametrize("url, some_entries, form_action, name_attr, verbose_name_plural", [ @pytest.mark.parametrize("url, some_entries, form_action, name_attr, verbose_name_plural", [
('/parlamentares/parlamentar/', some_parliamentarians, 'adiciona_parlamentar', 'nome_completo', 'Parlamentares'), ('/parlamentares/parlamentar/', some_parliamentarians, 'adiciona_parlamentar', 'nome_completo', 'Parlamentares'),
('/casas/casalegislativa/', some_parliaments, 'adicionar_casas', 'nome', 'Casas Legislativas'), ('/casas/orgao/', some_parliaments, 'adicionar_casas', 'nome', 'Casas Legislativas'),
]) ])
def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plural, app): def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plural, app):
@ -41,7 +41,7 @@ def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plu
@pytest.mark.parametrize("url, some_entries, all_expression", [ @pytest.mark.parametrize("url, some_entries, all_expression", [
('/parlamentares/parlamentar/', some_parliamentarians, 'todos os parlamentares', ), ('/parlamentares/parlamentar/', some_parliamentarians, 'todos os parlamentares', ),
('/casas/casalegislativa/', some_parliaments, 'todas as casas', ), ('/casas/orgao/', some_parliaments, 'todas as casas', ),
]) ])
def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_expression, app): def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_expression, app):
@ -56,7 +56,7 @@ def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_express
@pytest.mark.parametrize("url, generate_entries", [ @pytest.mark.parametrize("url, generate_entries", [
('/parlamentares/parlamentar/', parliamentarians_from_names, ), ('/parlamentares/parlamentar/', parliamentarians_from_names, ),
('/casas/casalegislativa/', parliaments_from_names, ), ('/casas/orgao/', parliaments_from_names, ),
]) ])
def test_pagination(url, generate_entries, app, live_server): def test_pagination(url, generate_entries, app, live_server):

4
templates/admin/change_list.html

@ -33,7 +33,6 @@
{% block coltype %}flex{% endblock %} {% block coltype %}flex{% endblock %}
{% block object-tools %} {% block object-tools %}
<ul class="object-tools pull-left nav nav-pills"> <ul class="object-tools pull-left nav nav-pills">
{% block object-tools-items %} {% block object-tools-items %}
{% if has_add_permission %} {% if has_add_permission %}
@ -46,7 +45,6 @@
{% endif %} {% endif %}
{% endblock %} {% endblock %}
</ul> </ul>
{% if cl.has_filters %} {% if cl.has_filters %}
<ul class="nav navbar-nav pull-right"> <ul class="nav navbar-nav pull-right">
<li class="dropdown"> <li class="dropdown">
@ -60,10 +58,10 @@
</ul> </ul>
{% endif %} {% endif %}
{% block search %}{% search_form cl %}{% endblock %} {% block search %}{% search_form cl %}{% endblock %}
{% endblock %} {% endblock %}
{% block content %} {% block content %}
{% block extra_search %}{% endblock %}
<form class="" id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>{% csrf_token %} <form class="" id="changelist-form" action="" method="post"{% if cl.formset.is_multipart %} enctype="multipart/form-data"{% endif %}>{% csrf_token %}
{% if cl.formset.errors %} {% if cl.formset.errors %}

Loading…
Cancel
Save