From d6099d082c2100ec364e336f8d3009920c782fcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Mon, 12 Apr 2021 01:06:47 -0300 Subject: [PATCH] Fix #20 --- etc/migracao/migra.py | 22 +-- locale/en/LC_MESSAGES/django.po | 2 +- scripts/importa_pesquisa.py | 50 +++---- .../verificacao_arquivos_faltando_media.py | 4 +- sigi/apps/casas/admin.py | 126 +++++++++--------- sigi/apps/casas/forms.py | 17 ++- .../management/commands/importa_gerentes.py | 34 ++--- .../migrations/0014_auto_20210406_1945.py | 31 +++++ .../migrations/0015_auto_20210407_0801.py | 28 ++++ .../migrations/0016_auto_20210407_1559.py | 20 +++ sigi/apps/casas/models.py | 51 ++++--- sigi/apps/casas/reports.py | 2 +- .../casas/lista_casas_carteira_snippet.html | 10 +- sigi/apps/casas/test_casas.py | 4 +- sigi/apps/casas/urls.py | 28 ++-- sigi/apps/casas/views.py | 36 ++--- sigi/apps/convenios/admin.py | 85 +++++++----- .../migrations/0003_auto_20210406_1945.py | 21 +++ .../migrations/0004_auto_20210407_1928.py | 78 +++++++++++ .../migrations/0005_auto_20210409_0842.py | 26 ++++ sigi/apps/convenios/models.py | 82 +++++++++--- .../templates/convenios/change_list.html | 70 ++++++++-- sigi/apps/convenios/views.py | 4 +- sigi/apps/diagnosticos/forms.py | 10 +- .../migrations/0004_auto_20210406_1945.py | 21 +++ sigi/apps/diagnosticos/models.py | 2 +- sigi/apps/diagnosticos/views.py | 6 +- .../migrations/0005_auto_20210406_1945.py | 27 ++++ sigi/apps/eventos/models.py | 34 ++--- sigi/apps/home/templatetags/menu_conf.yaml | 16 ++- sigi/apps/home/views.py | 52 ++++---- .../migrations/0002_auto_20210406_1945.py | 21 +++ sigi/apps/inventario/models.py | 2 +- .../migrations/0002_auto_20210406_1945.py | 21 +++ sigi/apps/metas/models.py | 4 +- sigi/apps/metas/templatetags/mapa_tags.py | 4 +- sigi/apps/metas/views.py | 44 +++--- .../migrations/0003_auto_20210406_1945.py | 21 +++ sigi/apps/ocorrencias/models.py | 8 +- sigi/apps/ocorrencias/views.py | 78 +++++------ .../migrations/0002_auto_20210406_1945.py | 27 ++++ sigi/apps/parlamentares/models.py | 6 +- sigi/apps/parlamentares/reports.py | 4 +- sigi/apps/parlamentares/views.py | 2 +- sigi/apps/servicos/admin.py | 9 +- .../migrations/0004_delete_casaatendida.py | 17 +++ .../migrations/0005_auto_20210406_1945.py | 27 ++++ .../servicos/migrations/0006_casaatendida.py | 25 ++++ sigi/apps/servicos/models.py | 10 +- .../servicos/casaatendida/change_list.html | 2 +- sigi/apps/servicos/views.py | 9 +- sigi/test_cart.py | 6 +- templates/admin/change_list.html | 4 +- 53 files changed, 934 insertions(+), 416 deletions(-) create mode 100644 sigi/apps/casas/migrations/0014_auto_20210406_1945.py create mode 100644 sigi/apps/casas/migrations/0015_auto_20210407_0801.py create mode 100644 sigi/apps/casas/migrations/0016_auto_20210407_1559.py create mode 100644 sigi/apps/convenios/migrations/0003_auto_20210406_1945.py create mode 100644 sigi/apps/convenios/migrations/0004_auto_20210407_1928.py create mode 100644 sigi/apps/convenios/migrations/0005_auto_20210409_0842.py create mode 100644 sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py create mode 100644 sigi/apps/eventos/migrations/0005_auto_20210406_1945.py create mode 100644 sigi/apps/inventario/migrations/0002_auto_20210406_1945.py create mode 100644 sigi/apps/metas/migrations/0002_auto_20210406_1945.py create mode 100644 sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py create mode 100644 sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py create mode 100644 sigi/apps/servicos/migrations/0004_delete_casaatendida.py create mode 100644 sigi/apps/servicos/migrations/0005_auto_20210406_1945.py create mode 100644 sigi/apps/servicos/migrations/0006_casaatendida.py diff --git a/etc/migracao/migra.py b/etc/migracao/migra.py index dc0cfff..b7f99e6 100755 --- a/etc/migracao/migra.py +++ b/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: diff --git a/locale/en/LC_MESSAGES/django.po b/locale/en/LC_MESSAGES/django.po index f7e49aa..709a9fe 100644 --- a/locale/en/LC_MESSAGES/django.po +++ b/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 diff --git a/scripts/importa_pesquisa.py b/scripts/importa_pesquisa.py index cac1c32..ad0c9c4 100644 --- a/scripts/importa_pesquisa.py +++ b/scripts/importa_pesquisa.py @@ -26,16 +26,16 @@ 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: - + Indicação de data e hora,Pesquisador,Câmara,Possui portal,Portal Modelo,URL,Observações - + Indicação de data e hora: Uma string datetime no formato %d/%m/%y %H:%M Pesquisador: O nome do servidor que realizou a pesquisa, conforme cadastrado no SIGI Câmara: A sigla da UF seguida de um espaço, seguido de um caracter - seguido de um espaço seguido do nome do município, @@ -43,19 +43,19 @@ def importa(file_list): Possui portal: Deve constar "sim" ou "não" indicando se a casa possui ou não portal. Portal Modelo: Deve constar "sim" ou "não" indicando se o portal da casa é o portal modelo ou não. URL: Deve conter a URL do portal da Casa. Opcionalmente pode ter alguma observação do pesquisador - Observações: Deve conter as observações do pesquisador, caso existam.''' - + Observações: Deve conter as observações do pesquisador, caso existam.''' + for filename in file_list: print 'Importando '+filename+'.csv' with open(filename+'.csv', 'rb') as infile: with open(filename+'.out', 'wb') as outfile: indata = csv.reader(infile, delimiter=',', quotechar='"') outdata = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) - + head = next(indata) head.append('Erros encontrados') outdata.writerow(head) - + for row in indata: data = row[0].strip() pesquisador = row[1].strip() @@ -64,32 +64,32 @@ def importa(file_list): pmodelo = row[4].strip() url = row[5].strip() obs = row[6].strip() - + if data == '': data = None else: data = datetime.strptime(data, '%d/%m/%y %H:%M') - + uf = uf_cidade[:2] 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 = '' - + for s in l: p = urlparse.urlparse(s) if p.netloc: url = s else: obs = obs + '\n' + s - + if pesquisador == '': servidor = None else: @@ -101,8 +101,8 @@ def importa(file_list): continue 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') @@ -114,18 +114,18 @@ def importa(file_list): continue else: casa = casa[0] - + casa.inclusao_digital = inclusao casa.data_levantamento = data casa.pesquisador = servidor - + if casa.pagina_web == '': casa.pagina_web = url else: obs = url + '\n' + obs - + casa.obs_pesquisa = obs casa.save() - - print 'O arquivo '+filename+'.out foi criado com os registros que nao puderam ser importados' - + + print 'O arquivo '+filename+'.out foi criado com os registros que nao puderam ser importados' + diff --git a/scripts/verificacao_arquivos_faltando_media.py b/scripts/verificacao_arquivos_faltando_media.py index 90cc79f..367b6f6 100644 --- a/scripts/verificacao_arquivos_faltando_media.py +++ b/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([ diff --git a/sigi/apps/casas/admin.py b/sigi/apps/casas/admin.py index ed511d9..7cd039e 100644 --- a/sigi/apps/casas/admin.py +++ b/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 """ - - Editar - """ % (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 """ - - Abrir PDF - """ % (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 """ +# +# Editar +# """ % (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 """ +# +# Abrir PDF +# """ % (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) diff --git a/sigi/apps/casas/forms.py b/sigi/apps/casas/forms.py index fcaf3a5..dca4889 100644 --- a/sigi/apps/casas/forms.py +++ b/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') + ': XXXXX-XXX.') 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")), @@ -34,7 +41,7 @@ class PortfolioForm(forms.Form): queryset=Servidor.objects.all(), label=_(u"Atribuir para") ) - + # O label precisa ser trocado dependendo da região que se está visualizando def __init__(self, label=_(u"Atribuir para"), *args, **kwargs): super(PortfolioForm, self).__init__(*args, **kwargs) diff --git a/sigi/apps/casas/management/commands/importa_gerentes.py b/sigi/apps/casas/management/commands/importa_gerentes.py index 5994980..ce3d009 100644 --- a/sigi/apps/casas/management/commands/importa_gerentes.py +++ b/sigi/apps/casas/management/commands/importa_gerentes.py @@ -25,41 +25,41 @@ 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 class Command(BaseCommand): args = u"data_file.csv" help = u"""Importa dados de atribuição de gerencia de relacionamentos de um arquivo CSV. - + A primeira linha do arquivo deve possuir um cabeçalho com os seguintes campos obrigatórios: - cod_municipio : Código IBGE do município - user_id : Nome de usuário (usado no login) do gerente de relacionamento da Casa - + * Os nomes dos campos devem ser grafados exatamente como descrito.""" - + campos = {'cod_municipio', 'user_id'} - + def handle(self, *args, **options): if len(args) != 1: raise CommandError(u"Informe UM arquivo csv a importar") - + file_name = args[0] - + if not os.path.isfile(file_name): raise CommandError(u"Arquivo %s não encontrado" % [file_name,]) - + with open(file_name, 'rb') as csvfile: reader = csv.DictReader(csvfile) - + if not self.campos.issubset(reader.fieldnames): raise CommandError(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 - + for reg in reader: try: municipio = Municipio.objects.get( @@ -86,13 +86,13 @@ 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() - + self.stdout.write(u"Importação concluída. {erros} erros em {linhas}" - u" linhas".format(erros=erros, + u" linhas".format(erros=erros, linhas=reader.line_num) ) \ No newline at end of file diff --git a/sigi/apps/casas/migrations/0014_auto_20210406_1945.py b/sigi/apps/casas/migrations/0014_auto_20210406_1945.py new file mode 100644 index 0000000..32ee5a2 --- /dev/null +++ b/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', + ), + ] diff --git a/sigi/apps/casas/migrations/0015_auto_20210407_0801.py b/sigi/apps/casas/migrations/0015_auto_20210407_0801.py new file mode 100644 index 0000000..93f7b4b --- /dev/null +++ b/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([]), + ), + ] diff --git a/sigi/apps/casas/migrations/0016_auto_20210407_1559.py b/sigi/apps/casas/migrations/0016_auto_20210407_1559.py new file mode 100644 index 0000000..91b5347 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/casas/models.py b/sigi/apps/casas/models.py index 71939c0..38548fd 100644 --- a/sigi/apps/casas/models.py +++ b/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( diff --git a/sigi/apps/casas/reports.py b/sigi/apps/casas/reports.py index e6e27c3..c2a380a 100644 --- a/sigi/apps/casas/reports.py +++ b/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') diff --git a/sigi/apps/casas/templates/casas/lista_casas_carteira_snippet.html b/sigi/apps/casas/templates/casas/lista_casas_carteira_snippet.html index bcd53a4..0b2e4d7 100644 --- a/sigi/apps/casas/templates/casas/lista_casas_carteira_snippet.html +++ b/sigi/apps/casas/templates/casas/lista_casas_carteira_snippet.html @@ -31,26 +31,26 @@ {% endfor %} - + - + - + - + {% if page_obj %}
@@ -64,7 +64,7 @@ {% for casa in page_obj.object_list %} - + diff --git a/sigi/apps/casas/test_casas.py b/sigi/apps/casas/test_casas.py index fe491ab..a2026ec 100644 --- a/sigi/apps/casas/test_casas.py +++ b/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] diff --git a/sigi/apps/casas/urls.py b/sigi/apps/casas/urls.py index 5381364..df6bf9f 100644 --- a/sigi/apps/casas/urls.py +++ b/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\w+)/report_complete/$', 'report_complete', name='report-complete-id'), + url(r'^orgao/report_complete/$', 'report_complete', name='report-complete-all'), + url(r'^orgao/(?P\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\w+)/labels/$', 'labels_report', name='labels-report-id'), + url(r'^orgao/labels/$', 'labels_report', name='labels-report-all'), + url(r'^orgao/(?P\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\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\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\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\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'), ) diff --git a/sigi/apps/casas/views.py b/sigi/apps/casas/views.py index 9b431e3..03a6243 100644 --- a/sigi/apps/casas/views.py +++ b/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() diff --git a/sigi/apps/convenios/admin.py b/sigi/apps/convenios/admin.py index f199c9a..f3b3311 100644 --- a/sigi/apps/convenios/admin.py +++ b/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,14 +34,23 @@ 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', 'data_termo_aceite', 'data_pub_diario', @@ -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): - 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 - 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 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 + 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) diff --git a/sigi/apps/convenios/migrations/0003_auto_20210406_1945.py b/sigi/apps/convenios/migrations/0003_auto_20210406_1945.py new file mode 100644 index 0000000..1fd1c84 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/convenios/migrations/0004_auto_20210407_1928.py b/sigi/apps/convenios/migrations/0004_auto_20210407_1928.py new file mode 100644 index 0000000..184bd66 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/convenios/migrations/0005_auto_20210409_0842.py b/sigi/apps/convenios/migrations/0005_auto_20210409_0842.py new file mode 100644 index 0000000..aa0a6d3 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/convenios/models.py b/sigi/apps/convenios/models.py index 59fbb07..9bafc84 100644 --- a/sigi/apps/convenios/models.py +++ b/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,52 +140,50 @@ 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) - + def get_termino_convenio(self): if (self.data_retorno_assinatura is None or self.duracao is None): return None - + ano = self.data_retorno_assinatura.year + int(self.duracao / 12) mes = int(self.data_retorno_assinatura.month + int(self.duracao % 12)) if mes > 12: ano = ano + 1 mes = mes - 12 dia = self.data_retorno_assinatura.day - + while True: try: data_fim = date(year=ano, month=mes,day=dia) break except: dia = dia - 1 - + 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(): return _(u"Vencido") return _(u"Vigente") - + if (self.data_retorno_assinatura is None and - self.data_devolucao_sem_assinatura is None and + self.data_devolucao_sem_assinatura is None and self.data_retorno_sem_assinatura is None): return _(u"Pendente") if (self.data_devolucao_sem_assinatura is not None or self.data_retorno_sem_assinatura is not None): return _(u"Desistência") - + return _(u"Indefinido") - + def get_sigad_url(self): m = re.match( r'(?P00100|00200)\.(?P\d{6})/(?P\d{4})-\d{2}', @@ -157,7 +197,7 @@ class Convenio(models.Model): r'&txt_numero_ano={ano}"' r' target="_blank">{processo}').format(processo=self.num_processo_sf,**m.groupdict()) return self.num_processo_sf - + def save(self, *args, **kwargs): self.conveniada = self.data_retorno_assinatura is not None self.equipada = self.data_termo_aceite is not None diff --git a/sigi/apps/convenios/templates/convenios/change_list.html b/sigi/apps/convenios/templates/convenios/change_list.html index 3f0ce3e..ccb9607 100644 --- a/sigi/apps/convenios/templates/convenios/change_list.html +++ b/sigi/apps/convenios/templates/convenios/change_list.html @@ -1,19 +1,61 @@ {% extends "change_list_with_cart.html" %} {% load i18n %} -{% block search %} -
- -
- - - - - - - - {% trans 'Datas podem ser: Um ano (aaaa), um mês (aaaa-mm) ou um dia (aaaa-mm-dd)' %} +{% block extra_search %} + +{% comment %} + +
+
+ + + + + + + +
-{% endblock %} + +{% endcomment %} +{% endblock %} \ No newline at end of file diff --git a/sigi/apps/convenios/views.py b/sigi/apps/convenios/views.py index 733dc18..a0a3710 100644 --- a/sigi/apps/convenios/views.py +++ b/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 diff --git a/sigi/apps/diagnosticos/forms.py b/sigi/apps/diagnosticos/forms.py index a271a1f..5ff92d5 100644 --- a/sigi/apps/diagnosticos/forms.py +++ b/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() diff --git a/sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py b/sigi/apps/diagnosticos/migrations/0004_auto_20210406_1945.py new file mode 100644 index 0000000..78a6bd0 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/diagnosticos/models.py b/sigi/apps/diagnosticos/models.py index c55739d..bf67c28 100644 --- a/sigi/apps/diagnosticos/models.py +++ b/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 diff --git a/sigi/apps/diagnosticos/views.py b/sigi/apps/diagnosticos/views.py index 2807abe..2b4dfba 100644 --- a/sigi/apps/diagnosticos/views.py +++ b/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}) diff --git a/sigi/apps/eventos/migrations/0005_auto_20210406_1945.py b/sigi/apps/eventos/migrations/0005_auto_20210406_1945.py new file mode 100644 index 0000000..17694f0 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/eventos/models.py b/sigi/apps/eventos/models.py index 721c63e..b678a62 100644 --- a/sigi/apps/eventos/models.py +++ b/sigi/apps/eventos/models.py @@ -3,18 +3,18 @@ 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 class TipoEvento(models.Model): nome = models.CharField(_(u"Nome"), max_length=100) - + class Meta: ordering = ("nome",) verbose_name, verbose_name_plural = _(u"Tipo de evento"), _(u"Tipos de evento") - + def __unicode__(self): return self.nome @@ -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) @@ -41,58 +41,58 @@ class Evento(models.Model): status = models.CharField(_(u"Status"), max_length=1, choices=STATUS_CHOICES) data_cancelamento = models.DateField(_(u"Data de cancelamento"), blank=True, null=True) motivo_cancelamento = models.TextField(_(u"Motivo do cancelamento"), blank=True) - + class Meta: ordering = ("-data_inicio",) verbose_name, verbose_name_plural = _(u"Evento"), _(u"Eventos") - + def __unicode__(self): return _("%(nome)s (%(tipo_evento)s): de %(data_inicio)s a %(data_termino)s") % dict( nome=self.nome, tipo_evento=unicode(self.tipo_evento), data_inicio=self.data_inicio, data_termino=self.data_termino) - - def save(self, *args, **kwargs): + + def save(self, *args, **kwargs): if self.status != 'C': self.data_cancelamento = None self.motivo_cancelamento = "" if self.data_inicio > self.data_termino: raise ValidationError(_(u"Data de término deve ser posterior à data de início")) return super(Evento, self).save(*args, **kwargs) - + class Funcao(models.Model): nome = models.CharField(_(u"Função na equipe de evento"), max_length=100) descricao = models.TextField(_(u"Descrição da função")) - + class Meta: ordering = ("nome",) verbose_name, verbose_name_plural = _(u"Função"), _(u"Funções") - + def __unicode__(self): return self.nome - + class Equipe(models.Model): evento = models.ForeignKey(Evento) membro = models.ForeignKey(Servidor, related_name="equipe_evento") funcao = models.ForeignKey(Funcao, verbose_name=_(u"Função na equipe")) observacoes = models.TextField(_(u"Observações"), blank=True) - + class Meta: ordering = ('evento', 'funcao', 'membro',) verbose_name, verbose_name_plural = _(u"Membro da equipe"), _(u"Membros da equipe") - + def __unicode__(self): return u"%s (%s)" % (unicode(self.membro), unicode(self.funcao),) - + 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) participou = models.BooleanField(_(u"Participou do evento"), default=False) - + class Meta: ordering = ('evento', 'casa', '-data_convite') unique_together = ('evento', 'casa') diff --git a/sigi/apps/home/templatetags/menu_conf.yaml b/sigi/apps/home/templatetags/menu_conf.yaml index afc56ae..4f7c310 100644 --- a/sigi/apps/home/templatetags/menu_conf.yaml +++ b/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: diff --git a/sigi/apps/home/views.py b/sigi/apps/home/views.py index 442f13f..1f6543b 100644 --- a/sigi/apps/home/views.py +++ b/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 @@ -58,7 +58,7 @@ def resumo_convenios(request): def resumo_seit(request): mes = request.GET.get('mes', None) ano = request.GET.get('ano', None) - + try: mes = datetime.date(year=int(ano), month=int(mes), day=1) tabela_resumo_seit = busca_informacoes_seit(mes) @@ -73,21 +73,21 @@ def resumo_seit(request): def chart_seit(request): mes = request.GET.get('mes', None) ano = request.GET.get('ano', None) - + try: mes = datetime.date(year=int(ano), month=int(mes), day=1) tabela_resumo_seit = busca_informacoes_seit(mes) except: tabela_resumo_seit = busca_informacoes_seit() - + data = { 'type': 'line', 'prevlink': reverse('home_chartseit') + ('?ano=%s&mes=%s' % (tabela_resumo_seit['mes_anterior'].year, - tabela_resumo_seit['mes_anterior'].month)), + tabela_resumo_seit['mes_anterior'].month)), 'nextlink': reverse('home_chartseit') + ('?ano=%s&mes=%s' % (tabela_resumo_seit['proximo_mes'].year, - tabela_resumo_seit['proximo_mes'].month)), + tabela_resumo_seit['proximo_mes'].month)), 'options': {'bezierCurve': False, 'datasetFill': False, 'pointDot': False, 'responsive': True}, 'data': { 'labels': ['%02d/%s' % (mes.month, mes.year) for mes in reversed(tabela_resumo_seit['meses'])], @@ -100,7 +100,7 @@ def chart_seit(request): for servico in tabela_resumo_seit['servicos']], } } - + return JsonResponse(data) @never_cache @@ -123,19 +123,19 @@ def chart_carteira(request): colors, highlights = color_palete() data = {'type': 'pie', 'options': {'responsive': True}, - 'data': [{'value': r['total_casas'], + 'data': [{'value': r['total_casas'], 'color': colors.next(), '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( 'gerentes_interlegis__nome_completo') ] } - + return JsonResponse(data) @never_cache @@ -144,11 +144,11 @@ 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 - + data = { 'type': 'pie', 'options': {'responsive': True}, @@ -184,14 +184,14 @@ def report_sem_convenio(request): casas = sc['total'] titulo = _(u"Casas sem convenio que utilizam algum serviço de registro " u"e/ou hospedagem") - + if fmt == 'csv': response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=casas.csv' writer = csv.writer(response) writer.writerow([titulo.encode('utf8')]) writer.writerow([u'']) - writer.writerow([u'casa', u'uf', u'gerentes', + writer.writerow([u'casa', u'uf', u'gerentes', u'serviços'.encode('utf8')]) for casa in casas: writer.writerow([ @@ -221,14 +221,14 @@ def report_sem_convenio(request): else: context = {'casas': casas, 'titulo': titulo} return render_to_pdf('home/sem_convenio.html', context) - - + + 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() @@ -297,7 +297,7 @@ def busca_informacoes_camara(): # Unindo as duas listass para que o cabecalho da esquerda fique junto com sua # respectiva linha lista_zip = zip(cabecalho_esquerda, linhas) - + # Retornando listas em forma de dicionario return { 'cabecalho_topo': cabecalho_topo, @@ -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, @@ -342,13 +342,13 @@ def busca_informacoes_seit(mes_atual=None): mes_atual = datetime.date.today().replace(day=1) mes_anterior = mes_atual - datetime.timedelta(days=1) proximo_mes = mes_atual + datetime.timedelta(days=calendar.monthrange(mes_atual.year, mes_atual.month)[1]) - + meses = [] mes = mes_atual for i in range(1, 13): meses.append(mes) mes = (mes - datetime.timedelta(days=1)).replace(day=1) - + result = { 'mes_atual': mes_atual, 'mes_anterior': mes_anterior, @@ -360,7 +360,7 @@ def busca_informacoes_seit(mes_atual=None): 'Novas casas em %s/%s' % (mes_atual.month, mes_atual.year) ], 'servicos': [], - } + } for tipo_servico in TipoServico.objects.all(): por_mes = [] @@ -374,7 +374,7 @@ def busca_informacoes_seit(mes_atual=None): 'novos_mes_anterior': tipo_servico.servico_set.filter(data_ativacao__year=mes_anterior.year, data_ativacao__month=mes_anterior.month).count(), 'novos_mes_atual': tipo_servico.servico_set.filter(data_ativacao__year=mes_atual.year, data_ativacao__month=mes_atual.month).count(), 'novos_por_mes': por_mes, - 'cor': colors.next(), + 'cor': colors.next(), } ) @@ -410,5 +410,5 @@ def color_palete(): '#B3B6F1', '#BB9098', '#BDF1ED', ]) - + return (colors, highlights) diff --git a/sigi/apps/inventario/migrations/0002_auto_20210406_1945.py b/sigi/apps/inventario/migrations/0002_auto_20210406_1945.py new file mode 100644 index 0000000..0473f66 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/inventario/models.py b/sigi/apps/inventario/models.py index e86a5e0..cdb67cc 100644 --- a/sigi/apps/inventario/models.py +++ b/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( diff --git a/sigi/apps/metas/migrations/0002_auto_20210406_1945.py b/sigi/apps/metas/migrations/0002_auto_20210406_1945.py new file mode 100644 index 0000000..c590ad0 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/metas/models.py b/sigi/apps/metas/models.py index 3ca3c36..e7d5a90 100644 --- a/sigi/apps/metas/models.py +++ b/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) diff --git a/sigi/apps/metas/templatetags/mapa_tags.py b/sigi/apps/metas/templatetags/mapa_tags.py index 79039a6..273176a 100644 --- a/sigi/apps/metas/templatetags/mapa_tags.py +++ b/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) diff --git a/sigi/apps/metas/views.py b/sigi/apps/metas/views.py index f2f9ff4..0cf636c 100644 --- a/sigi/apps/metas/views.py +++ b/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 @@ -76,7 +76,7 @@ def mapa(request): [(x.sigla, x.sigla, x.nome, True) for x in TipoServico.objects.all()]), ("convenios", _(u'Por Casas conveniadas'), - [(x.sigla, + [(x.sigla, 'convenio_' + x.sigla, _(u'ao {projeto}').format(projeto=x.sigla), x.sigla == 'PML') for x in projetos]), @@ -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]} @@ -225,11 +225,11 @@ def map_list(request): srv = {x[0]: x[1] for x in TipoServico.objects.values_list('id', 'nome')} cnv = {x[0]: x[1] for x in Projeto.objects.values_list('id', 'sigla')} - - head = [s.encode('utf-8') for s in + + head = [s.encode('utf-8') for s in [u'código IBGE', u'nome da casa', u'município', u'UF', u'região', ] + [x for x in srv.values()] + - reduce(lambda x, y: x + y, + reduce(lambda x, y: x + y, [['conveniada ao %s' % x, 'equipada por %s' % x] for x in cnv.values()])] writer.writerow(head) @@ -240,7 +240,7 @@ def map_list(request): casa.municipio.nome.encode('utf-8'), casa.municipio.uf.sigla.encode('utf-8'), casa.municipio.uf.get_regiao_display().encode('utf-8'), ] - + for id in srv.keys(): try: sv = casa.servico_set.get(tipo_servico__id=id) @@ -286,27 +286,27 @@ def filtrar_casas(seit, convenios, equipadas, regioes, estados, diagnosticos, qConvenio = Q(convenio__projeto__sigla__in=convenios) qEquipada = Q(convenio__projeto__sigla__in=equipadas, convenio__equipada=True) - + qRegiao = Q(municipio__uf__regiao__in=regioes) qEstado = Q(municipio__uf__sigla__in=estados) - + if gerentes: qGerente = Q(gerentes_interlegis__id__in=gerentes) else: qGerente = Q() if diagnosticos: - qDiagnostico = Q(diagnostico__publicado__in=[p == 'P' + qDiagnostico = Q(diagnostico__publicado__in=[p == 'P' for p in 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) else: - casas = casas.filter(Q(servico=None) & Q(convenio=None) & + casas = casas.filter(Q(servico=None) & Q(convenio=None) & Q(diagnostico=None)) return casas @@ -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 @@ -369,7 +369,7 @@ def parliament_summary(parliament): 'equipadas': [], 'info': [] } - + if parliament.gerentes_interlegis.exists(): summary['info'].append(_(u"Gerentes Interlegis: {lista}").format( lista=parliament.lista_gerentes(fmt='lista'))) @@ -378,14 +378,14 @@ def parliament_summary(parliament): summary['info'].append( _(u"{name} ativado em {date}").format( name=sv.tipo_servico.nome, - date=sv.data_ativacao.strftime('%d/%m/%Y') if sv.data_ativacao + date=sv.data_ativacao.strftime('%d/%m/%Y') if sv.data_ativacao else _(u'')) + (u" ").format(sv.url, STATIC_URL)) summary['seit'].append(sv.tipo_servico.sigla) for cv in parliament.convenio_set.all(): - if ((cv.data_retorno_assinatura is None) and + if ((cv.data_retorno_assinatura is None) and (cv.equipada and cv.data_termo_aceite is not None)): summary['info'].append( _(u"Equipada em {date} pelo {project}").format( @@ -397,7 +397,7 @@ def parliament_summary(parliament): _(u"Adesão ao projeto {project}, em {date}").format( project=cv.projeto.sigla, date=cv.data_adesao)) summary['convenios'].append(cv.projeto.sigla) - if ((cv.data_retorno_assinatura is not None) and not + if ((cv.data_retorno_assinatura is not None) and not (cv.equipada and cv.data_termo_aceite is not None)): summary['info'].append( _(u"Conveniada ao %(project)s em %(date)s").format( @@ -421,8 +421,8 @@ def parliament_summary(parliament): _(u"Diagnosticada no período de {initial_date} " u"a {final_date}").format( initial_date=dg.data_visita_inicio.strftime('%d/%m/%Y') - if dg.data_visita_inicio is not None - else _(u""), + if dg.data_visita_inicio is not None + else _(u""), final_date=dg.data_visita_fim.strftime('%d/%m/%Y') if dg.data_visita_fim else _(u""))) diff --git a/sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py b/sigi/apps/ocorrencias/migrations/0003_auto_20210406_1945.py new file mode 100644 index 0000000..03ef359 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/ocorrencias/models.py b/sigi/apps/ocorrencias/models.py index 2bfe120..0774147 100644 --- a/sigi/apps/ocorrencias/models.py +++ b/sigi/apps/ocorrencias/models.py @@ -34,7 +34,7 @@ class Ocorrencia(models.Model): STATUS_RESOLVIDO = 3 STATUS_FECHADO = 4 STATUS_DUPLICADO = 5 - + STATUS_CHOICES = ( (STATUS_ABERTO , _(u'Aberto')), (STATUS_REABERTO , _(u'Reaberto')), @@ -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) @@ -80,7 +80,7 @@ class Ocorrencia(models.Model): if self.ticket is not None and Ocorrencia.objects.exclude(pk=self.pk).filter(ticket=self.ticket).exists(): raise ValidationError({'ticket': _(u"Já existe ocorrência registrada para este ticket")}) return super(Ocorrencia, self).clean() - + def get_ticket_url(self): return mark_safe(settings.OSTICKET_URL % self.ticket) @@ -91,7 +91,7 @@ class Comentario(models.Model): usuario = models.ForeignKey('servidores.Servidor', verbose_name=_(u'Usuário')) novo_status = models.IntegerField(_(u'Novo status'), choices=Ocorrencia.STATUS_CHOICES, blank=True, null=True) encaminhar_setor = models.ForeignKey('servidores.Servico', verbose_name=_(u'Encaminhar para setor'), blank=True, null=True) - + def save(self, *args, **kwargs): if self.encaminhar_setor and (self.encaminhar_setor != self.ocorrencia.setor_responsavel): self.ocorrencia.setor_responsavel = self.encaminhar_setor diff --git a/sigi/apps/ocorrencias/views.py b/sigi/apps/ocorrencias/views.py index 640fc4c..d5d8296 100644 --- a/sigi/apps/ocorrencias/views.py +++ b/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 @@ -20,33 +20,33 @@ def painel_ocorrencias(request): tipo = request.GET.get('type', None) id = request.GET.get('id', None) painel = request.GET.get('painel', None) - + data = {} - + if tipo is None or tipo == 'error': tipo = 'servidor' u = get_object_or_404(Servidor, user=request.user) id = u.pk - + if id is None: 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, uf=casa.municipio.uf.sigla - ) + ) elif tipo == 'servidor': servidor = get_object_or_404(Servidor, pk=id) panel_title = servidor.nome_completo - + paineis = {'gerente': u"Minhas casas", 'servico': u"Meu setor", '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( @@ -54,10 +54,10 @@ def painel_ocorrencias(request): painel = 'servico' else: painel = 'timeline' - + data.update({'paineis': paineis, 'painel': painel, 'servidor': servidor}) - + if painel == 'gerente': ocorrencias = Ocorrencia.objects.filter( casa_legislativa__gerentes_interlegis=servidor) @@ -87,7 +87,7 @@ def painel_ocorrencias(request): 'anexo_set' ) ocorrencias = ocorrencias.annotate(total_anexos=Count('anexo')) - + data.update( {'ocorrencias': ocorrencias, 'panel_title': panel_title, @@ -96,7 +96,7 @@ def painel_ocorrencias(request): 'PRIORITY_CHOICES': Ocorrencia.PRIORITY_CHOICES } ) - + return render(request, 'ocorrencias/painel.html', data) @login_required @@ -106,22 +106,22 @@ def busca_nominal(request, origin="tudo"): return JsonResponse([{'label': _(u'Erro na pesquisa por termo'), 'value': 'type=error'}], safe=False) data = [] - - if origin == "casa" or origin == "tudo": - casas = CasaLegislativa.objects.filter(search_text__icontains=to_ascii(term)).select_related('municipio', 'municipio__uf')[:10] + + if origin == "casa" or origin == "tudo": + casas = Orgao.objects.filter(search_text__icontains=to_ascii(term)).select_related('municipio', 'municipio__uf')[:10] data += [{'value': c.pk, 'label': "%s, %s" % (c.nome, c.municipio.uf.sigla,), 'origin': 'casa'} for c in casas] - - if origin == "servidor" or origin == "tudo": + + if origin == "servidor" or origin == "tudo": servidores = Servidor.objects.filter(nome_completo__icontains=term)[:10] data += [{'value': s.pk, 'label': s.nome_completo, 'origin': 'servidor'} for s in servidores] - + if origin == "servico" or origin == "tudo": setores = Servico.objects.filter(nome__icontains=term) | Servico.objects.filter(sigla__icontains=term) setores = setores[:10] data += [{'value': s.pk, 'label': '%s - %s' % (s.sigla, s.nome), 'origin': 'servico'} for s in setores] - + data = sorted(data, key=lambda d: d['label']) - + return JsonResponse(data, safe=False) @login_required @@ -129,44 +129,44 @@ def busca_nominal(request, origin="tudo"): def muda_prioridade(request): id_ocorrencia = request.POST.get('id_ocorrencia', None) prioridade = request.POST.get('prioridade', None) - + if id_ocorrencia is None or prioridade is None: return JsonResponse({'result': 'error', 'message': _(u'Erro nos parâmetros')}) - + if not any([int(prioridade) == p[0] for p in Ocorrencia.PRIORITY_CHOICES]): return JsonResponse({'result': 'error', 'message': _(u'Valor de prioridade não aceito')}) - + try: ocorrencia = Ocorrencia.objects.get(pk=id_ocorrencia) except Exception as e: return JsonResponse({'result': 'error', 'message': str(e)}) - + ocorrencia.prioridade = prioridade ocorrencia.save() - + return JsonResponse({'result': 'success', 'message': _(u'Prioridade alterada')}) @login_required def exclui_anexo(request): anexo_id = request.GET.get('anexo_id', None) - + if anexo_id is None: return JsonResponse({'result': 'error', 'message': _(u'Erro nos parâmetros')}) - + try: anexo = Anexo.objects.get(pk=anexo_id) except Exception as e: return JsonResponse({'result': 'error', 'message': str(e)}) - + ocorrencia = anexo.ocorrencia anexo.delete() - + link_label = (ungettext('%s arquivo anexo', '%s arquivos anexos', ocorrencia.anexo_set.count()) % (ocorrencia.anexo_set.count(),)) painel = render_to_string('ocorrencias/anexos_snippet.html', {'ocorrencia': ocorrencia}, context_instance=RequestContext(request)) - + return JsonResponse({'result': 'success', 'message': _(u'Anexo %s excluído com sucesso' % (anexo_id,)), 'link_label': link_label, 'anexos_panel': painel}) @@ -176,7 +176,7 @@ def inclui_anexo(request): form = AnexoForm(request.POST, request.FILES) if form.is_valid(): anexo = form.save() - return HttpResponse('' % + return HttpResponse('' % escape(anexo.ocorrencia_id)) else: ocorrencia = form.instance.ocorrencia @@ -186,7 +186,7 @@ def inclui_anexo(request): form = AnexoForm(instance=Anexo(ocorrencia=ocorrencia)) return render(request, 'ocorrencias/anexo_form.html', {'form': form, 'ocorrencia': ocorrencia, 'is_popup': True}) - + @login_required def anexo_snippet(request): ocorrencia_id = request.GET.get('ocorrencia_id', None) @@ -205,19 +205,19 @@ def inclui_comentario(request): form = ComentarioForm() else: ocorrencia = form.instance.ocorrencia - + painel = render_to_string('ocorrencias/ocorrencia_snippet.html', {'ocorrencia': ocorrencia, 'comentario_form': form,}, context_instance=RequestContext(request)) - + return JsonResponse({'ocorrencia_id': ocorrencia.id, 'ocorrencia_panel': painel}) @login_required @require_POST def inclui_ocorrencia(request): form = OcorrenciaForm(request.POST) - + data = {} - + if form.is_valid(): ocorrencia = form.save(commit=False) ocorrencia.servidor_registro = Servidor.objects.get(user=request.user) @@ -230,9 +230,9 @@ def inclui_ocorrencia(request): context_instance=RequestContext(request)) else: data['result'] = 'error' - + data['ocorrencia_form'] = render_to_string('ocorrencias/ocorrencia_form.html', {'ocorrencia_form': form}, context_instance=RequestContext(request)) - + return JsonResponse(data) \ No newline at end of file diff --git a/sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py b/sigi/apps/parlamentares/migrations/0002_auto_20210406_1945.py new file mode 100644 index 0000000..b645ba0 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/parlamentares/models.py b/sigi/apps/parlamentares/models.py index 2d80d38..238b62e 100644 --- a/sigi/apps/parlamentares/models.py +++ b/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') ) diff --git a/sigi/apps/parlamentares/reports.py b/sigi/apps/parlamentares/reports.py index adbe021..4e076b0 100644 --- a/sigi/apps/parlamentares/reports.py +++ b/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): diff --git a/sigi/apps/parlamentares/views.py b/sigi/apps/parlamentares/views.py index 33d66e4..d7f2090 100644 --- a/sigi/apps/parlamentares/views.py +++ b/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 diff --git a/sigi/apps/servicos/admin.py b/sigi/apps/servicos/admin.py index 74f5765..9dcb4b9 100644 --- a/sigi/apps/servicos/admin.py +++ b/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() diff --git a/sigi/apps/servicos/migrations/0004_delete_casaatendida.py b/sigi/apps/servicos/migrations/0004_delete_casaatendida.py new file mode 100644 index 0000000..6e42dc8 --- /dev/null +++ b/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', + ), + ] diff --git a/sigi/apps/servicos/migrations/0005_auto_20210406_1945.py b/sigi/apps/servicos/migrations/0005_auto_20210406_1945.py new file mode 100644 index 0000000..0a86dc2 --- /dev/null +++ b/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, + ), + ] diff --git a/sigi/apps/servicos/migrations/0006_casaatendida.py b/sigi/apps/servicos/migrations/0006_casaatendida.py new file mode 100644 index 0000000..6a58804 --- /dev/null +++ b/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',), + ), + ] diff --git a/sigi/apps/servicos/models.py b/sigi/apps/servicos/models.py index 02c228c..74b344e 100644 --- a/sigi/apps/servicos/models.py +++ b/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) @@ -219,4 +219,4 @@ class RegistroServico(models.Model): class Meta: verbose_name_plural = _(u'Registro de serviços') - + diff --git a/sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html b/sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html index 11d0569..104fd94 100644 --- a/sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html +++ b/sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html @@ -15,7 +15,7 @@ function dismissRelatedLookupPopup(win, chosenId) { {% block object-tools-items %}
  • + href="{% url 'admin:casas_orgao_changelist' %}?codigo_interlegis__exact=" class="addlink"> {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
  • diff --git a/sigi/apps/servicos/views.py b/sigi/apps/servicos/views.py index ab7a47c..d49bcd9 100644 --- a/sigi/apps/servicos/views.py +++ b/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()} diff --git a/sigi/test_cart.py b/sigi/test_cart.py index d9d7d53..eb4df2f 100644 --- a/sigi/test_cart.py +++ b/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): diff --git a/templates/admin/change_list.html b/templates/admin/change_list.html index 5dbbabb..f1a7f8a 100644 --- a/templates/admin/change_list.html +++ b/templates/admin/change_list.html @@ -33,7 +33,6 @@ {% block coltype %}flex{% endblock %} {% block object-tools %} - - {% if cl.has_filters %} {% endif %} {% block search %}{% search_form cl %}{% endblock %} - {% endblock %} {% block content %} +{% block extra_search %}{% endblock %}
    {% csrf_token %} {% if cl.formset.errors %}
    {{ casa.nome }}{{ casa.nome }} {{ casa.municipio.uf.get_regiao_display }} {{ casa.municipio.uf }} {{ casa.municipio.microrregiao.mesorregiao }}