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

2
locale/en/LC_MESSAGES/django.po

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

12
scripts/importa_pesquisa.py

@ -26,11 +26,11 @@ import csv
import urlparse
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
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:
@ -74,11 +74,11 @@ def importa(file_list):
cidade = uf_cidade[5:]
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':
inclusao = CasaLegislativa.INCLUSAO_DIGITAL_CHOICES[3][0]
inclusao = Orgao.INCLUSAO_DIGITAL_CHOICES[3][0]
else:
inclusao = CasaLegislativa.INCLUSAO_DIGITAL_CHOICES[2][0]
inclusao = Orgao.INCLUSAO_DIGITAL_CHOICES[2][0]
l = url.splitlines()
url = ''
@ -102,7 +102,7 @@ def importa(file_list):
else:
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()
if cc == 0:
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 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.diagnosticos.models import Anexo as AnexoDiagnosticos
from sigi.apps.ocorrencias.models import Anexo as AnexoOcorrencias
@ -31,7 +31,7 @@ def url(obj):
# IMAGENS FALTANDO
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():
if a.foto:
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 image_cropping import ImageCroppingMixin
from sigi.apps.casas.forms import CasaLegislativaForm
from sigi.apps.casas.models import CasaLegislativa, Presidente, Funcionario, TipoOrgao
from sigi.apps.casas.forms import OrgaoForm
from sigi.apps.casas.models import Orgao, Presidente, Funcionario, TipoOrgao
from sigi.apps.casas.views import report_complete, labels_report, export_csv, \
labels_report_sem_presidente, report, \
adicionar_casas_carrinho
from sigi.apps.contatos.models import Telefone
from sigi.apps.convenios.models import Convenio, Projeto
from sigi.apps.diagnosticos.models import Diagnostico
from sigi.apps.inventario.models import Bem
# from sigi.apps.diagnosticos.models import Diagnostico
# from sigi.apps.inventario.models import Bem
from sigi.apps.metas.models import PlanoDiretor
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.servidores.models import Servidor
from sigi.apps.utils import queryset_ascii
@ -129,7 +129,7 @@ class ConveniosInline(admin.TabularInline):
return ""
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"
elif status == u"Vigente":
label = r"success"
@ -164,51 +164,47 @@ class ConveniosInline(admin.TabularInline):
link_sigad.short_description = _("Processo no Senado")
link_sigad.allow_tags = True
class LegislaturaInline(admin.TabularInline):
model = Legislatura
fields = ['numero', 'data_inicio', 'data_fim', 'data_eleicao', 'total_parlamentares', 'link_parlamentares', ]
readonly_fields = ['link_parlamentares', ]
def link_parlamentares(self, obj):
if obj.pk is None:
return ""
from django.core.urlresolvers import reverse
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=[obj.pk])
url = url + '?_popup=1'
return """<input id="edit_legislatura-%s" type="hidden"/>
<a id="lookup_edit_legislatura-%s" href="%s" class="changelink" onclick="return showRelatedObjectLookupPopup(this)">
Editar
</a>""" % (obj.pk, obj.pk, url)
link_parlamentares.short_description = _(u'Parlamentares')
link_parlamentares.allow_tags = True
class DiagnosticoInline(admin.TabularInline):
model = Diagnostico
fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ]
readonly_fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ]
extra = 0
max_num = 0
can_delete = False
def link_diagnostico(self, obj):
if obj.pk is None:
return ""
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=["%s.pdf" % obj.pk])
return """<input id="edit_diagnostico-%s" type="hidden"/>
<a id="lookup_edit_diagnostico-%s" href="%s" class="button" target="_blank">
Abrir PDF
</a>""" % (obj.pk, obj.pk, url)
link_diagnostico.short_description = _(u'Ver PDF')
link_diagnostico.allow_tags = True
class BemInline(admin.TabularInline):
model = Bem
# class LegislaturaInline(admin.TabularInline):
# model = Legislatura
# fields = ['numero', 'data_inicio', 'data_fim', 'data_eleicao', 'total_parlamentares', 'link_parlamentares', ]
# readonly_fields = ['link_parlamentares', ]
# def link_parlamentares(self, obj):
# if obj.pk is None:
# return ""
# from django.core.urlresolvers import reverse
# url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=[obj.pk])
# url = url + '?_popup=1'
# return """<input id="edit_legislatura-%s" type="hidden"/>
# <a id="lookup_edit_legislatura-%s" href="%s" class="changelink" onclick="return showRelatedObjectLookupPopup(this)">
# Editar
# </a>""" % (obj.pk, obj.pk, url)
# link_parlamentares.short_description = _(u'Parlamentares')
# link_parlamentares.allow_tags = True
# class DiagnosticoInline(admin.TabularInline):
# model = Diagnostico
# fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ]
# readonly_fields = ['data_visita_inicio', 'data_visita_fim', 'publicado', 'data_publicacao', 'responsavel', 'link_diagnostico', ]
# extra = 0
# max_num = 0
# can_delete = False
# def link_diagnostico(self, obj):
# if obj.pk is None:
# return ""
# url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=["%s.pdf" % obj.pk])
# return """<input id="edit_diagnostico-%s" type="hidden"/>
# <a id="lookup_edit_diagnostico-%s" href="%s" class="button" target="_blank">
# Abrir PDF
# </a>""" % (obj.pk, obj.pk, url)
# link_diagnostico.short_description = _(u'Ver PDF')
# link_diagnostico.allow_tags = True
# class BemInline(admin.TabularInline):
# model = Bem
class ServicoInline(admin.TabularInline):
model = Servico
@ -218,10 +214,8 @@ class ServicoInline(admin.TabularInline):
max_num = 0
can_delete = False
class PlanoDiretorInline(admin.TabularInline):
model = PlanoDiretor
# class PlanoDiretorInline(admin.TabularInline):
# model = PlanoDiretor
class OcorrenciaInline(admin.TabularInline):
model = Ocorrencia
@ -309,12 +303,11 @@ class ServicoFilter(admin.SimpleListFilter):
return queryset.distinct('municipio__uf__nome', 'nome')
class CasaLegislativaAdmin(ImageCroppingMixin, BaseModelAdmin):
form = CasaLegislativaForm
class OrgaoAdmin(ImageCroppingMixin, BaseModelAdmin):
form = OrgaoForm
actions = ['adicionar_casas', ]
inlines = (TelefonesInline, PresidenteInline, FuncionariosInline,
ConveniosInline, LegislaturaInline, DiagnosticoInline, BemInline,
ServicoInline, PlanoDiretorInline, OcorrenciaInline,)
ConveniosInline, ServicoInline, OcorrenciaInline,)
list_display = ('nome', 'get_uf', 'get_gerentes', 'get_convenios',
'get_servicos')
list_display_links = ('nome',)
@ -342,7 +335,7 @@ class CasaLegislativaAdmin(ImageCroppingMixin, BaseModelAdmin):
}),
)
raw_id_fields = ('municipio',)
readonly_fields = ['num_parlamentares', ]
readonly_fields = ['num_parlamentares', 'gerentes_interlegis',]
search_fields = ('search_text', 'cnpj', 'bairro', 'logradouro',
'cep', 'municipio__nome', 'municipio__uf__nome',
'municipio__codigo_ibge', 'pagina_web', 'observacoes')
@ -374,14 +367,17 @@ class CasaLegislativaAdmin(ImageCroppingMixin, BaseModelAdmin):
get_servicos.allow_tags = True
def changelist_view(self, request, extra_context=None):
return super(CasaLegislativaAdmin, self).changelist_view(
return super(OrgaoAdmin, self).changelist_view(
request,
extra_context={'query_str': '?' + request.META['QUERY_STRING']}
)
def lookup_allowed(self, lookup, value):
return super(CasaLegislativaAdmin, self).lookup_allowed(lookup, value) or \
lookup in ['municipio__uf__codigo_ibge__exact', 'convenio__projeto__id__exact']
return (super(OrgaoAdmin, self).lookup_allowed(lookup, value) or
lookup in ['tipo__legislativo__exact',
'tipo__sigla__exact',
'municipio__uf__codigo_ibge__exact',
'convenio__projeto__id__exact'])
def etiqueta(self, request, 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")
def get_actions(self, request):
actions = super(CasaLegislativaAdmin, self).get_actions(request)
actions = super(OrgaoAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
admin.site.register(CasaLegislativa, CasaLegislativaAdmin)
admin.site.register(Orgao, OrgaoAdmin)
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 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
class CasaLegislativaForm(forms.ModelForm):
class OrgaoForm(forms.ModelForm):
# cnpj = BRCNPJField(
# label=_(u'CNPJ'),
# required=False,
@ -16,9 +16,16 @@ class CasaLegislativaForm(forms.ModelForm):
cep = BRZipCodeField(label=_(u'CEP'), help_text=_(u'Formato') + ': <em>XXXXX-XXX</em>.')
class Meta:
model = CasaLegislativa
model = Orgao
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):
ACAO_CHOICES = (
('ADD', _(u"Adicionar")),

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

@ -25,7 +25,7 @@
import csv
import os
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.contatos.models import Municipio
@ -56,7 +56,7 @@ class Command(BaseCommand):
if not self.campos.issubset(reader.fieldnames):
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
@ -87,7 +87,7 @@ class Command(BaseCommand):
erros = erros + 1
continue
for casa in municipio.casalegislativa_set.filter(
for casa in municipio.orgao_set.filter(
tipo__sigla__in=['AL', 'CM']):
casa.gerentes_interlegis.add(gerente)
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
from string import ascii_uppercase
from unicodedata import normalize
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from django.contrib.contenttypes import generic
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.utils import SearchField
class TipoOrgao(models.Model):
""" Modelo para representar o tipo da Casa Legislativa
Geralmente: Câmara Municipal, Assembléia Legislativa,
@ -23,6 +22,7 @@ class TipoOrgao(models.Model):
sigla = models.CharField(_(u"Sigla"), max_length=5)
nome = models.CharField(_(u"Nome"), max_length=100)
legislativo = models.BooleanField(_(u"Poder legislativo"), default=False)
class Meta:
verbose_name = _(u"Tipo de órgão")
@ -31,9 +31,7 @@ class TipoOrgao(models.Model):
def __unicode__(self):
return self.nome
class CasaLegislativa(models.Model):
class Orgao(models.Model):
""" Modelo para representar uma Casa Legislativa
"""
@ -72,7 +70,8 @@ class CasaLegislativa(models.Model):
gerentes_interlegis = models.ManyToManyField(
Servidor,
verbose_name=_(u"Gerentes Interlegis"),
related_name='casas_que_gerencia'
related_name='casas_que_gerencia',
blank=True,
)
# Informações de contato
@ -143,9 +142,8 @@ class CasaLegislativa(models.Model):
class Meta:
ordering = ('nome',)
unique_together = ('municipio', 'tipo')
verbose_name = _(u'Casa Legislativa')
verbose_name_plural = _(u'Casas Legislativas')
verbose_name = _(u'Órgão')
verbose_name_plural = _(u'Órgãos')
def lista_gerentes(self, fmt='html'):
if not self.gerentes_interlegis.exists():
@ -210,7 +208,7 @@ class CasaLegislativa(models.Model):
if codigo == '':
if self.tipo.sigla == 'AL': # Assembléias são tratadas a parte
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
self.codigo_interlegis = codigo
self.save()
@ -243,7 +241,7 @@ class CasaLegislativa(models.Model):
cityName = cityName.replace(' ', '')
ultima = len(cityName)
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \
while Orgao.objects.filter(codigo_interlegis=codigo). \
count() > 0 and ultima > 0:
codigo = codigo[:2] + cityName[ultima - 1: ultima]
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
# 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', '').\
replace('I', '').replace('O', '').replace('U', '')[:3]
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
# Se ainda não gerou um nome único, vamos colocar dígitos no
@ -264,7 +262,7 @@ class CasaLegislativa(models.Model):
i = 'A'
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \
while Orgao.objects.filter(codigo_interlegis=codigo). \
count() > 0 and i <= 'Z':
codigo = codigo[:2] + str(i)
i = chr(ord(i) + 1)
@ -275,7 +273,7 @@ class CasaLegislativa(models.Model):
i = 0
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \
while Orgao.objects.filter(codigo_interlegis=codigo). \
count() > 0 and i < 100:
codigo = random.choice(cityName) + random.choice(cityName) + \
random.choice(cityName)
@ -286,10 +284,8 @@ class CasaLegislativa(models.Model):
i = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
while CasaLegislativa.objects.filter(codigo_interlegis=codigo). \
count() > 0:
codigo = random.choice(i) + random.choice(i) + \
random.choice(i)
while Orgao.objects.filter(codigo_interlegis=codigo).count() > 0:
codigo = random.choice(i) + random.choice(i) + random.choice(i)
self.codigo_interlegis = codigo
self.save()
@ -299,11 +295,22 @@ class CasaLegislativa(models.Model):
def __unicode__(self):
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):
address_changed = False
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
self.bairro != original.bairro or
self.municipio != original.municipio or
@ -315,7 +322,7 @@ class CasaLegislativa(models.Model):
if address_changed:
self.ult_alt_endereco = datetime.now()
return super(CasaLegislativa, self).save(*args, **kwargs)
return super(Orgao, self).save(*args, **kwargs)
class Funcionario(models.Model):
@ -343,7 +350,7 @@ class Funcionario(models.Model):
("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.alphabetic_filter = True
sexo = models.CharField(

2
sigi/apps/casas/reports.py

@ -52,7 +52,7 @@ class CasasLegislativasLabels(Report):
Usage example::
>>> 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.generate_by(PDFGenerator, filename='./inline-detail-report.pdf')

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

@ -64,7 +64,7 @@
</tr>
{% for casa in page_obj.object_list %}
<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 }}</td>
<td>{{ casa.municipio.microrregiao.mesorregiao }}</td>

4
sigi/apps/casas/test_casas.py

@ -1,7 +1,7 @@
import pytest
from django_dynamic_fixture import G
from sigi.apps.casas.models import CasaLegislativa
from sigi.apps.casas.models import Orgao
@pytest.fixture
@ -14,4 +14,4 @@ def some_parliaments():
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',
# Informacoes de uma casa legislativa
url(r'^casalegislativa/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/report_complete/$', 'report_complete', name='report-complete-all'),
url(r'^orgao/(?P<id>\w+)/report_complete/$', 'report_complete', name='report-complete-id'),
# Reports Labels
url(r'^casalegislativa/labels/$', 'labels_report', name='labels-report-all'),
url(r'^casalegislativa/(?P<id>\w+)/labels/$', 'labels_report', name='labels-report-id'),
url(r'^orgao/labels/$', 'labels_report', name='labels-report-all'),
url(r'^orgao/(?P<id>\w+)/labels/$', 'labels_report', name='labels-report-id'),
# Reports Labels Parlamentar
url(r'^casalegislativa/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/labels_parlamentar/$', 'labels_report_parlamentar', name='lebels-report-parlamentar-all'),
url(r'^orgao/(?P<id>\w+)/labels_parlamentar/$', 'labels_report_parlamentar', name='labels-report-parlamentar-id'),
# Reports labels sem presidente
url(r'^casalegislativa/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/labels_sem_presidente/$', 'labels_report_sem_presidente', name='labels-report-sem-presidente-all'),
url(r'^orgao/(?P<id>\w+)/labels_sem_presidente/$', 'labels_report_sem_presidente', name='labels-report-sem-presidente-id'),
# Reports casas sem convenio
url(r'^casalegislativa/reports/$', 'report', name='casa-report'),
url(r'^casalegislativa/casas_sem_convenio_report/$', 'casas_sem_convenio_report', name='casas-sem-convenio-report'),
url(r'^orgao/reports/$', 'report', name='casa-report'),
url(r'^orgao/casas_sem_convenio_report/$', 'casas_sem_convenio_report', name='casas-sem-convenio-report'),
# CSV
url(r'^casalegislativa/csv/$', 'export_csv', name='casa-export-csv'), # Error
url(r'^orgao/csv/$', 'export_csv', name='casa-export-csv'), # Error
# Carrinho
url(r'^casalegislativa/carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'),
url(r'^casalegislativa/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/$', 'visualizar_carrinho', name='visualizar-carrinho'),
url(r'^orgao/carrinho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-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'^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 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,
CasasLegislativasLabelsSemPresidente)
from sigi.apps.contatos.models import UnidadeFederativa, Mesorregiao, Microrregiao
@ -25,8 +25,8 @@ from sigi.shortcuts import render_to_pdf
# @param qs: queryset
# @param o: (int) number of order field
def query_ordena(qs, o):
from sigi.apps.casas.admin import CasaLegislativaAdmin
list_display = CasaLegislativaAdmin.list_display
from sigi.apps.casas.admin import OrgaoAdmin
list_display = OrgaoAdmin.list_display
order_fields = []
for order_number in o.split('.'):
@ -95,9 +95,9 @@ def carrinhoOrGet_for_qs(request):
"""
if 'carrinho_casas' in request.session:
ids = request.session['carrinho_casas']
qs = CasaLegislativa.objects.filter(pk__in=ids)
qs = Orgao.objects.filter(pk__in=ids)
else:
qs = CasaLegislativa.objects.all()
qs = Orgao.objects.all()
if request.GET:
qs = get_for_qs(request.GET, 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)
if id:
qs = CasaLegislativa.objects.filter(pk=id)
qs = Orgao.objects.filter(pk=id)
else:
qs = carrinhoOrGet_for_qs(request)
@ -214,7 +214,7 @@ def labels_report_parlamentar(request, id=None, formato='3x9_etiqueta'):
formato = request.POST['tamanho_etiqueta']
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])
parlamentares = [m.parlamentar for m in mandatos]
qs = parlamentares
@ -239,12 +239,12 @@ def carrinhoOrGet_for_parlamentar_qs(request):
"""
if 'carrinho_casas' in request.session:
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])
parlamentares = [m.parlamentar for m in mandatos]
qs = parlamentares
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])
parlamentares = [m.parlamentar for m in mandatos]
qs = parlamentares
@ -259,7 +259,7 @@ def labels_report_sem_presidente(request, id=None, formato='2x5_etiqueta'):
"""
if id:
qs = CasaLegislativa.objects.filter(pk=id)
qs = Orgao.objects.filter(pk=id)
else:
qs = carrinhoOrGet_for_qs(request)
@ -285,7 +285,7 @@ def report(request, id=None, tipo=None):
return report_complete(request, id)
if id:
qs = CasaLegislativa.objects.filter(pk=id)
qs = Orgao.objects.filter(pk=id)
else:
qs = carrinhoOrGet_for_qs(request)
@ -302,7 +302,7 @@ def report(request, id=None, tipo=None):
def report_complete(request, id=None):
if id:
qs = CasaLegislativa.objects.filter(pk=id)
qs = Orgao.objects.filter(pk=id)
else:
qs = carrinhoOrGet_for_qs(request)
@ -314,7 +314,7 @@ def report_complete(request, id=None):
@login_required
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:
qs = get_for_qs(request.GET, qs)
@ -454,7 +454,7 @@ def portfolio(request):
name=unicode(microrregiao))
)
data['querystring'] = 'micro={0}'.format(microrregiao.pk)
casas = CasaLegislativa.objects.filter(
casas = Orgao.objects.filter(
municipio__microrregiao=microrregiao
)
elif meso_id:
@ -470,7 +470,7 @@ def portfolio(request):
_(u'Atribuir casas da mesorregiao {name} para').format(
name=unicode(mesorregiao)))
data['querystring'] = 'meso={0}'.format(mesorregiao.pk)
casas = CasaLegislativa.objects.filter(
casas = Orgao.objects.filter(
municipio__microrregiao__mesorregiao=mesorregiao
)
elif uf_id:
@ -483,7 +483,7 @@ def portfolio(request):
_(u'Atribuir casas do estado {name} para').format(
name=unicode(uf)))
data['querystring'] = 'uf={0}'.format(uf.pk)
casas = CasaLegislativa.objects.filter(municipio__uf=uf)
casas = Orgao.objects.filter(municipio__uf=uf)
elif regiao:
data['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
x[0] == regiao][0]))
data['querystring'] = 'regiao={0}'.format(regiao)
casas = CasaLegislativa.objects.filter(municipio__uf__regiao=regiao)
casas = Orgao.objects.filter(municipio__uf__regiao=regiao)
if casas:
casas = casas.order_by('municipio__uf',
@ -687,7 +687,7 @@ def painel_relacionamento(request):
casas = gerente.casas_que_gerencia.all()
if gerente is None or not casas.exists():
casas = CasaLegislativa.objects.exclude(gerentes_interlegis=None)
casas = Orgao.objects.exclude(gerentes_interlegis=None)
gerente = None
tipos_servico = TipoServico.objects.all()

79
sigi/apps/convenios/admin.py

@ -4,29 +4,27 @@ from django.http import HttpResponse, HttpResponseRedirect
from django.utils.translation import ugettext as _
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.views import adicionar_convenios_carrinho
from sigi.apps.utils import queryset_ascii
from sigi.apps.utils.base_admin import BaseModelAdmin
from sigi.apps.servidores.models import Servidor
class TramitacaoInline(admin.TabularInline):
model = Tramitacao
extra = 1
# class TramitacaoInline(admin.TabularInline):
# model = Tramitacao
# extra = 1
class AnexosInline(admin.TabularInline):
model = Anexo
extra = 2
exclude = ['data_pub', ]
class EquipamentoPrevistoInline(admin.TabularInline):
model = EquipamentoPrevisto
extra = 2
raw_id_fields = ('equipamento',)
# class EquipamentoPrevistoInline(admin.TabularInline):
# model = EquipamentoPrevisto
# extra = 2
# raw_id_fields = ('equipamento',)
class AnexoAdmin(BaseModelAdmin):
date_hierarchy = 'data_pub'
@ -36,13 +34,22 @@ class AnexoAdmin(BaseModelAdmin):
search_fields = ('descricao', 'convenio__id', 'arquivo',
'convenio__casa_legislativa__nome')
class AcompanhaFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs):
super(AcompanhaFilter, self).__init__(*args, **kwargs)
servidores = Servidor.objects.filter(
convenio__isnull=False).order_by('nome_completo').distinct()
self.lookup_choices = [(x.id, x) for x in servidores]
class ConvenioAdmin(BaseModelAdmin):
change_list_template = 'convenios/change_list.html'
fieldsets = (
(None,
{'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'),
{'fields': ('data_adesao', 'data_retorno_assinatura', 'duracao',
@ -53,15 +60,16 @@ class ConvenioAdmin(BaseModelAdmin):
{'fields': ('data_devolucao_sem_assinatura', 'data_retorno_sem_assinatura',)}
),
)
readonly_fields = ('data_sigi',)
actions = ['adicionar_convenios']
inlines = (TramitacaoInline, AnexosInline, EquipamentoPrevistoInline)
inlines = (AnexosInline,)
list_display = ('num_convenio', 'casa_legislativa', 'get_uf',
'status_convenio', 'link_sigad', 'data_adesao',
'data_retorno_assinatura', 'duracao', 'data_pub_diario',
'data_termo_aceite', 'projeto',
)
'status_convenio', 'link_sigad', 'data_retorno_assinatura',
'duracao', 'projeto', 'status', 'acompanha',)
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'
ordering = ('casa_legislativa__tipo__sigla', 'casa_legislativa__municipio__uf', 'casa_legislativa')
raw_id_fields = ('casa_legislativa',)
@ -79,7 +87,7 @@ class ConvenioAdmin(BaseModelAdmin):
return ""
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"
elif status == u"Vigente":
label = r"success"
@ -101,24 +109,26 @@ class ConvenioAdmin(BaseModelAdmin):
link_sigad.allow_tags = True
def changelist_view(self, request, extra_context=None):
def normaliza_data(nome_param):
import re
request.GET._mutable = True
if 'data_retorno_assinatura__gte' in request.GET:
value = request.GET.get('data_retorno_assinatura__gte', '')
if value == '':
del request.GET['data_retorno_assinatura__gte']
elif re.match('^\d*$', value): # Year only
request.GET['data_retorno_assinatura__gte'] = "%s-01-01" % value # Complete with january 1st
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 nome_param in request.GET:
value = request.GET.get(nome_param, '')
if value == '':
del request.GET['data_retorno_assinatura__lte']
del request.GET[nome_param]
elif re.match('^\d*$', value): # Year only
request.GET['data_retorno_assinatura__lte'] = "%s-01-01" % value # Complete with january 1st
# Complete with january 1st
request.GET[nome_param] = "%s-01-01" % value
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
# Complete with 1st day of month
request.GET[nome_param] = '%s-01' % value
request.GET._mutable = True
normaliza_data('data_retorno_assinatura__gte')
normaliza_data('data_retorno_assinatura__lte')
normaliza_data('data_sigad__gte')
normaliza_data('data_sigad__lte')
normaliza_data('data_sigi__gte')
normaliza_data('data_sigi__lte')
request.GET._mutable = False
return super(ConvenioAdmin, self).changelist_view(
@ -169,5 +179,6 @@ class EquipamentoPrevistoAdmin(BaseModelAdmin):
'equipamento__modelo__modelo', 'equipamento__modelo__tipo__tipo')
admin.site.register(Projeto)
admin.site.register(StatusConvenio)
admin.site.register(Convenio, ConvenioAdmin)
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.utils.translation import ugettext as _
from sigi.apps.utils import SearchField
from sigi.apps.servidores.models import Servidor
class Projeto(models.Model):
@ -17,6 +18,17 @@ class Projeto(models.Model):
def __unicode__(self):
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):
@ -29,8 +41,8 @@ class Convenio(models.Model):
um pacto de colaboração entre as partes
"""
casa_legislativa = models.ForeignKey(
'casas.CasaLegislativa',
verbose_name=_(u'Casa Legislativa')
'casas.Orgao',
verbose_name=_(u'órgão conveniado')
)
# campo de busca em caixa baixa e sem acentos
search_text = SearchField(field_names=['casa_legislativa'])
@ -47,19 +59,49 @@ class Convenio(models.Model):
max_length=10,
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(
_(u'Aderidas'),
_(u'aderidas'),
null=True,
blank=True,
)
data_retorno_assinatura = models.DateField(
_(u'Conveniadas'),
_(u'conveniadas'),
null=True,
blank=True,
help_text=_(u'Convênio firmado.')
)
duracao = models.PositiveIntegerField(
_(u"Duração (meses)"),
_(u"duração (meses)"),
null=True,
blank=True,
help_text=_(u"Deixar em branco caso a duração seja indefinida")
@ -70,7 +112,7 @@ class Convenio(models.Model):
blank=True
)
data_termo_aceite = models.DateField(
_(u'Equipadas'),
_(u'equipadas'),
null=True,
blank=True,
help_text=_(u'Equipamentos recebidos.')
@ -98,11 +140,6 @@ class Convenio(models.Model):
blank=True,
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)
equipada = models.BooleanField(default=False)
@ -128,6 +165,9 @@ class Convenio(models.Model):
return data_fim
def get_status(self):
if self.status and self.status.cancela:
return _(u"Cancelado")
if self.data_retorno_assinatura is not None:
if self.duracao is not None:
if date.today() >= self.get_termino_convenio():

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

@ -1,19 +1,61 @@
{% extends "change_list_with_cart.html" %}
{% load i18n %}
{% block search %}
<div id="toolbar">
<form id="changelist-search" action="" method="get">
<div><!-- DIV needed for valid HTML -->
<label for="searchbar"><img src="/static/admin/img/icon_searchbox.png" alt="Search" /></label>
<input type="text" size="40" name="q" value="" id="searchbar" />
{% block extra_search %}
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Filtro de datas</a>
<p class="navbar-text">Use AAAA, AAAA-MM ou AAAA-MM-DD</p>
</div>
<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" size="10" name="data_retorno_assinatura__gte" value="" id="data_retorno_assinatura__gte" class="vDateField"/>
<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" size="10" name="data_retorno_assinatura__lte" value="" id="data_retorno_assinatura__lte" />
<input type="submit" value="Pesquisar" />
{% trans 'Datas podem ser: Um ano (aaaa), um mês (aaaa-mm) ou um dia (aaaa-mm-dd)' %}
<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>
</form>
{% endcomment %}
{% 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 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.convenios.models import Convenio, Projeto
from sigi.apps.convenios.reports import ConvenioPorCMReport, ConvenioPorALReport, ConvenioReportSemAceiteAL, ConvenioReportSemAceiteCM
@ -249,7 +249,7 @@ def report_regiao(request, regiao='NE'):
projetos = Projeto.objects.all()
camaras = CasaLegislativa.objects.filter(tipo__sigla='CM')
camaras = Orgao.objects.filter(tipo__sigla='CM')
tabelas = list()
# 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.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.diagnosticos.models import Diagnostico
from sigi.apps.diagnosticos.widgets import EavCheckboxSelectMultiple, EavRadioSelect
@ -132,23 +132,23 @@ class DiagnosticoMobileForm(BaseDynamicEntityForm):
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_criacao = forms.DateField()
class Meta:
model = CasaLegislativa
model = Orgao
fields = ('cnpj', 'data_criacao', 'data_instalacao', 'logradouro', 'bairro', 'cep', 'email', 'pagina_web')
def __init__(self, *args, **kwargs):
super(CasaLegislativaMobileForm, self).__init__(*args, **kwargs)
super(OrgaoMobileForm, self).__init__(*args, **kwargs)
self.fields['data_criacao'] = forms.DateField(
label=_(u'Data de criação do Município'),
initial=self.instance.municipio.data_criacao,
required=False)
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']
if commit:
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
"""
casa_legislativa = models.ForeignKey(
'casas.CasaLegislativa',
'casas.Orgao',
verbose_name=_(u'Casa Legislativa'))
# 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.diagnosticos.decorators import validate_diagnostico
from sigi.apps.diagnosticos.forms import (DiagnosticoMobileForm,
CasaLegislativaMobileForm, FuncionariosMobileForm)
OrgaoMobileForm, FuncionariosMobileForm)
from sigi.apps.diagnosticos.models import Diagnostico, Categoria, Pergunta
from sigi.apps.diagnosticos.urls import LOGIN_REDIRECT_URL
from sigi.apps.utils.decorators import login_required
@ -117,7 +117,7 @@ def categoria_casa_legislativa(request, id_diagnostico):
casa_legislativa = diagnostico.casa_legislativa
if request.method == "POST":
form = CasaLegislativaMobileForm(request.POST,
form = OrgaoMobileForm(request.POST,
instance=casa_legislativa)
if form.is_valid():
form.save()
@ -133,7 +133,7 @@ def categoria_casa_legislativa(request, id_diagnostico):
json = simplejson.dumps(resposta)
return HttpResponse(json, content_type='application/json')
else:
form = CasaLegislativaMobileForm(instance=casa_legislativa)
form = OrgaoMobileForm(instance=casa_legislativa)
context = RequestContext(request, {'form': form,
'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.utils.functional import lazy
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.servidores.models import Servidor
from django.core.exceptions import ValidationError
@ -33,7 +33,7 @@ class Evento(models.Model):
solicitante = models.CharField(_(u"Solicitante"), max_length=100)
data_inicio = models.DateField(_(u"Data de início"))
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)
municipio = models.ForeignKey(Municipio)
local = models.TextField(_(u"Local do evento"), blank=True)
@ -87,7 +87,7 @@ class Equipe(models.Model):
class Convite(models.Model):
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"))
data_convite = models.DateField(_(u"Data do convite"))
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/
- title: Mesorregiões
url: contatos/mesorregiao/
- title: Casas Legislativas
url: casas/casalegislativa/
- title: Casas e órgãos
url: casas/orgao/
children:
- title: Todas
url: casas/casalegislativa/
- title: Todo legislativo
url: casas/orgao/?tipo__legislativo__exact=1
- title: Câmaras Municipais
url: casas/casalegislativa/?tipo__id__exact=1
url: casas/orgao/?tipo__sigla__exact=CM
- 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
url: casas/portfolio/
- title: Carteira de relacionamentos
@ -50,6 +52,8 @@ main_menu:
url: convenios/convenio/
- title: Planos diretores
url: metas/planodiretor/
- title: Tabela de acompanhamento
url: convenios/statusconvenio/
# - title: Inventário
# url: inventario/bem/
# children:

14
sigi/apps/home/views.py

@ -27,7 +27,7 @@ import calendar
from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext as _
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.diagnosticos.models import Diagnostico
from sigi.apps.metas.models import Meta
@ -128,7 +128,7 @@ def chart_carteira(request):
'highlight': highlights.next(),
'label': r['gerentes_interlegis__nome_completo']
}
for r in CasaLegislativa.objects.exclude(
for r in Orgao.objects.exclude(
gerentes_interlegis=None).values(
'gerentes_interlegis__nome_completo').annotate(
total_casas=Count('pk')).order_by(
@ -144,7 +144,7 @@ def chart_performance(request):
servidor = request.GET.get('servidor', None)
if servidor is None:
casas = CasaLegislativa.objects.exclude(gerentes_interlegis=None)
casas = Orgao.objects.exclude(gerentes_interlegis=None)
else:
gerente = get_object_or_404(Servidor, pk=servidor)
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
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')
projetos = Projeto.objects.all()
@ -309,10 +309,10 @@ def busca_informacoes_camara():
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')
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')
total = Orgao.objects.exclude(servico=None).filter(servico__data_desativacao=None, convenio=None).order_by('municipio__uf__sigla', 'nome').distinct('municipio__uf__sigla', 'nome')
hospedagem = Orgao.objects.exclude(servico=None).filter(servico__data_desativacao=None, servico__tipo_servico__modo='H', convenio=None).order_by('municipio__uf__sigla', 'nome').distinct('municipio__uf__sigla', 'nome')
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 {
'total': total,
'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):
casa_legislativa = models.ForeignKey('casas.CasaLegislativa')
casa_legislativa = models.ForeignKey('casas.Orgao')
equipamento = models.ForeignKey(Equipamento)
fornecedor = models.ForeignKey(Fornecedor)
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.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.diagnosticos.models import Diagnostico
from sigi.apps.financeiro.models import Desembolso
@ -115,7 +115,7 @@ class PlanoDiretor(models.Model):
('I', _(u'Implantado')),
)
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
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)

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

@ -2,7 +2,7 @@
from django import template
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
@ -11,7 +11,7 @@ register = template.Library()
@register.filter(name='map_desc_serv')
def descricao_servicos(casa):
if not isinstance(casa, CasaLegislativa):
if not isinstance(casa, Orgao):
return ""
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 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.convenios.models import Projeto
from sigi.apps.financeiro.models import Desembolso
@ -128,9 +128,9 @@ def map_search(request):
q = request.GET.get('q')
if len(q.split(',')) > 1:
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:
casas = CasaLegislativa.objects.filter(search_text__icontains=to_ascii(q))
casas = Orgao.objects.filter(search_text__icontains=to_ascii(q))
if casas.count() > 0:
response = {'result': 'FOUND', 'ids': [c.pk for c in casas]}
@ -301,7 +301,7 @@ def filtrar_casas(seit, convenios, equipadas, regioes, estados, diagnosticos,
else:
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:
casas = casas.filter(qServico | qConvenio | qEquipada | qDiagnostico)
@ -323,7 +323,7 @@ def gera_map_data_file(cronjob=False):
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:
# continue
# # 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')),
)
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_cl_tipo_filter = 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 import RequestContext
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.servidores.models import Servidor, Servico
from sigi.apps.ocorrencias.models import Ocorrencia, Anexo
@ -32,7 +32,7 @@ def painel_ocorrencias(request):
raise Http404("id não definido")
if tipo == 'casa':
casa = get_object_or_404(CasaLegislativa, pk=id)
casa = get_object_or_404(Orgao, pk=id)
ocorrencias = casa.ocorrencia_set.all()
panel_title = u"{casa}, {uf}".format(
casa=casa.nome,
@ -46,7 +46,7 @@ def painel_ocorrencias(request):
'timeline': u"Comentados por mim"}
if painel is None:
if CasaLegislativa.objects.filter(
if Orgao.objects.filter(
gerentes_interlegis=servidor).count() > 0:
painel = 'gerente'
elif Ocorrencia.objects.filter(
@ -108,7 +108,7 @@ def busca_nominal(request, origin="tudo"):
data = []
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]
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.utils.translation import ugettext as _
from sigi.apps.casas.models import CasaLegislativa
from sigi.apps.casas.models import Orgao
class Partido(models.Model):
@ -82,7 +82,7 @@ class Mandato(models.Model):
class Legislatura(models.Model):
casa_legislativa = models.ForeignKey(CasaLegislativa)
casa_legislativa = models.ForeignKey(Orgao)
numero = models.PositiveSmallIntegerField(_(u'número legislatura'))
data_inicio = models.DateField(_(u'início'))
data_fim = models.DateField(_(u'fim'))
@ -174,7 +174,7 @@ class SessaoLegislativa(models.Model):
class MesaDiretora(models.Model):
casa_legislativa = models.ForeignKey(
'casas.CasaLegislativa',
'casas.Orgao',
verbose_name=_(u'Casa Legislativa')
)

4
sigi/apps/parlamentares/reports.py

@ -47,7 +47,7 @@ class ParlamentaresLabels(Report):
Usage example::
>>> 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.generate_by(PDFGenerator, filename='./inline-detail-report.pdf')
@ -268,7 +268,7 @@ def label_text(text):
return "%s: " % text
class InfoCasaLegislativa(ReportDefault):
class InfoOrgao(ReportDefault):
title = _(u'Casa Legislativa')
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.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.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 sigi.apps.casas.admin import FuncionariosInline
from sigi.apps.casas.models import CasaLegislativa
from sigi.apps.servicos.models import Servico, LogServico, CasaAtendida, TipoServico
from sigi.apps.casas.models import Orgao
from sigi.apps.servicos.models import (Servico, LogServico, CasaAtendida,
TipoServico)
from sigi.apps.utils.base_admin import BaseModelAdmin
@ -163,7 +164,7 @@ class ServicoAdmin(BaseModelAdmin):
if not id_casa:
raise Http404
obj.casa_legislativa = CasaAtendida.objects.get(pk=id_casa)
obj.casa_legislativa = Orgao.objects.get(pk=id_casa)
return obj
@ -210,7 +211,7 @@ class CasaAtendidaAdmin(BaseModelAdmin):
def change_view(self, request, object_id, extra_context=None):
# Se a Casa ainda não é atendida, gerar o código interlegis para ela
# Assim ela passa a ser uma casa atendida
casa = CasaLegislativa.objects.get(id=object_id)
casa = Orgao.objects.get(id=object_id)
if casa.codigo_interlegis == '':
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 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 _
@ -37,7 +37,7 @@ class TipoServico(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'))
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)
@ -183,7 +183,7 @@ class CasaAtendidaManager(models.Manager):
return qs
class CasaAtendida(CasaLegislativa):
class CasaAtendida(Orgao):
class Meta:
proxy = True
@ -193,7 +193,7 @@ class CasaAtendida(CasaLegislativa):
class CasaManifesta(models.Model):
casa_legislativa = models.OneToOneField(CasaLegislativa)
casa_legislativa = models.OneToOneField(Orgao)
data_manifestacao = models.DateTimeField(auto_now_add=True)
data_atualizacao = models.DateTimeField(auto_now=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 %}
<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>
{% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
</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.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.servicos.models import TipoServico, CasaAtendida, CasaManifesta, ServicoManifesto
from sigi.apps.servicos.models import (TipoServico, CasaManifesta, CasaAtendida,
ServicoManifesto)
class MapaView(TemplateView):
@ -75,7 +76,7 @@ class CasaManifestaProtoForm(forms.Form):
def casa_manifesta_view(request):
if 'casa_id' in request.GET:
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
@ -138,7 +139,7 @@ def casa_manifesta_view(request):
extra_context = {'casa': casa, 'cmf': cmf}
elif 'uf' in request.GET:
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:
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", [
('/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):
@ -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", [
('/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):
@ -56,7 +56,7 @@ def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_express
@pytest.mark.parametrize("url, generate_entries", [
('/parlamentares/parlamentar/', parliamentarians_from_names, ),
('/casas/casalegislativa/', parliaments_from_names, ),
('/casas/orgao/', parliaments_from_names, ),
])
def test_pagination(url, generate_entries, app, live_server):

4
templates/admin/change_list.html

@ -33,7 +33,6 @@
{% block coltype %}flex{% endblock %}
{% block object-tools %}
<ul class="object-tools pull-left nav nav-pills">
{% block object-tools-items %}
{% if has_add_permission %}
@ -46,7 +45,6 @@
{% endif %}
{% endblock %}
</ul>
{% if cl.has_filters %}
<ul class="nav navbar-nav pull-right">
<li class="dropdown">
@ -60,10 +58,10 @@
</ul>
{% endif %}
{% block search %}{% search_form cl %}{% endblock %}
{% endblock %}
{% 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 %}
{% if cl.formset.errors %}

Loading…
Cancel
Save