Browse Source

Refatora app parlamentares p/ utilizar ref do Crud

pull/675/head
LeandroRoberto 8 years ago
parent
commit
0dfb6c306d
  1. 8
      sapl/base/templatetags/menus.py
  2. 2
      sapl/comissoes/views.py
  3. 3
      sapl/crispy_layout_mixin.py
  4. 167
      sapl/crud/base.py
  5. 2
      sapl/materia/views.py
  6. 24
      sapl/parlamentares/migrations/0032_frenteproxymasterdetail.py
  7. 29
      sapl/parlamentares/migrations/0033_auto_20160930_1715.py
  8. 18
      sapl/parlamentares/migrations/0034_delete_frenteparlamentar.py
  9. 5
      sapl/parlamentares/urls.py
  10. 356
      sapl/parlamentares/views.py
  11. 2
      sapl/templates/crud/detail.html
  12. 4
      sapl/templates/crud/detail_detail.html
  13. 14
      sapl/templates/crud/list.html
  14. 10
      sapl/templates/parlamentares/coligacao_detail.html
  15. 4
      sapl/templates/parlamentares/composicaomesa_form.html
  16. 21
      sapl/templates/parlamentares/frentes.html
  17. 8
      sapl/templates/parlamentares/subnav.yaml
  18. 5
      sapl/templates/parlamentares/subnav_coligacao.yaml
  19. 25
      scripts/inicializa_grupos_autorizacoes.py

8
sapl/base/templatetags/menus.py

@ -1,6 +1,7 @@
import yaml
from django import template
from django.core.urlresolvers import reverse
import yaml
register = template.Library()
@ -32,8 +33,6 @@ def subnav(context, path=None):
execução deste subnav. Inicialmente, a maneira mais prática encontrada
de isolar foi com o teste abaixo.
"""
if 'sistema' in request.path:
return
rm = request.resolver_match
app_template = rm.app_name.rsplit('.', 1)[-1]
@ -45,6 +44,9 @@ def subnav(context, path=None):
else:
yaml_path = '%s/%s' % (app_template, 'subnav.yaml')
if not yaml_path:
return
try:
"""
Por padrão, são carragados dois Loaders,

2
sapl/comissoes/views.py

@ -52,7 +52,7 @@ class ComissaoCrud(Crud):
class BaseMixin(Crud.BaseMixin):
list_field_names = ['nome', 'sigla', 'tipo', 'data_criacao', 'ativa']
initial_order = '-ativa', 'sigla'
ordering = '-ativa', 'sigla'
class ListView(Crud.ListView):
permission_required = []

3
sapl/crispy_layout_mixin.py

@ -149,6 +149,9 @@ class CrispyLayoutFormMixin:
This base implementation returns the field names
in the first fieldset of the layout.
'''
obj = self.crud if hasattr(self, 'crud') else self
if hasattr(obj, 'list_field_names'):
return obj.list_field_names
rows = self.get_layout()[0][1:]
return [fieldname for row in rows for fieldname, __ in row]

167
sapl/crud/base.py

@ -17,7 +17,7 @@ from django.utils.translation import string_concat
from django.utils.translation import ugettext_lazy as _
from django.views.generic import (CreateView, DeleteView, DetailView, ListView,
UpdateView)
from django.views.generic.base import ContextMixin
from django.views.generic.base import ContextMixin, View
from django.views.generic.list import MultipleObjectMixin
from sapl.crispy_layout_mixin import CrispyLayoutFormMixin, get_field_display
@ -79,6 +79,7 @@ def make_pagination(index, num_pages):
"""
variáveis do crud:
help_path
container_field
container_field_set
is_m2m
@ -90,10 +91,9 @@ variáveis do crud:
permission_required -> este atributo ser vazio não nulo torna a view publ
layout_key_set
layout_key
ordered_list = False desativa os clicks e controles de ord da listagem
parent_field = parentesco reverso separado por '__'
initial_order = deve ser um elemento de list_field_names
FIXME: as setas indicativas de ordem em crud/list.html
não está se comportando como esperado para initial_order descrescente
namespace
"""
@ -214,8 +214,11 @@ class CrudBaseMixin(CrispyLayoutFormMixin):
self.model_name_set = getattr(
obj.model, obj.model_set).field.model._meta.model_name
if hasattr(self, 'permission_required') and\
self.permission_required:
if hasattr(self, 'permission_required') and self.permission_required:
if hasattr(obj, 'public'):
self.permission_required = list(
set(self.permission_required) - set(obj.public))
self.permission_required = tuple((
self.permission(pr) for pr in self.permission_required))
@ -225,8 +228,8 @@ class CrudBaseMixin(CrispyLayoutFormMixin):
def url_name_set(self, suffix):
obj = self.crud if hasattr(self, 'crud') else self
return '%s_%s' % (getattr(
obj.model, obj.model_set).field.model._meta.model_name, suffix)
return '%s_%s' % (getattr(obj.model, obj.model_set
).field.model._meta.model_name, suffix)
def permission(self, rad):
return '%s%s%s' % (self.app_label if rad.endswith('_') else '',
@ -250,6 +253,10 @@ class CrudBaseMixin(CrispyLayoutFormMixin):
return reverse('%s:%s' % (namespace, self.url_name_set(suffix)),
args=args)
@property
def ordered_list(self):
return True
@property
def list_url(self):
obj = self.crud if hasattr(self, 'crud') else self
@ -338,20 +345,37 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
para junção de fields via tuplas.
list_field_names pode ser construido como
list_field_names=('nome', 'endereco', ('telefone', sexo'), 'dat_nasc')
ou ainda:
list_field_names = ['composicao__comissao__nome', 'cargo__nome', (
'composicao__periodo__data_inicio', 'composicao__periodo__data_fim')]
"""
r = []
for fieldname in self.list_field_names:
if isinstance(fieldname, tuple):
s = [force_text(self.model._meta.get_field(
fn).verbose_name) for fn in fieldname]
if not isinstance(fieldname, tuple):
fieldname = fieldname,
s = []
for fn in fieldname:
m = self.model
fn = fn.split('__')
for f in fn:
f = m._meta.get_field(f)
if hasattr(f, 'related_model') and f.related_model:
m = f.related_model
if m == self.model:
s.append(force_text(f.verbose_name))
else:
s.append(force_text(m._meta.verbose_name))
s = ' / '.join(s)
r.append(s)
else:
r.append(
self.model._meta.get_field(fieldname).verbose_name)
return r
def _as_row(self, obj):
"""
FIXME: Refatorar função para capturar url correta em caso de uso de
campos foreignkey. getHeaders faz isso para construir o título.
falta fazer com esta função
"""
r = []
for i, name in enumerate(self.list_field_names):
url = self.resolve_url(
@ -420,6 +444,8 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
del qr['page']
context['filter_url'] = (
'&' + qr.urlencode()) if len(qr) > 0 else ''
if self.ordered_list:
if 'o' in qr:
del qr['o']
context['ordering_url'] = (
@ -447,6 +473,7 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
if q:
queryset = queryset.filter(q)
if self.ordered_list:
list_field_names = self.list_field_names
o = '1'
desc = ''
@ -454,7 +481,8 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
o = self.request.GET['o']
desc = '-' if o.startswith('-') else ''
# Constroi a ordenação da listagem com base no que o usuário clicar
# Constroi a ordenação da listagem com base no que o usuário
# clicar
try:
fields_for_ordering = list_field_names[
(abs(int(o)) - 1) % len(list_field_names)]
@ -465,8 +493,15 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
ordering = ()
model = self.model
for fo in fields_for_ordering:
fm = None
try:
fm = model._meta.get_field(fo)
if hasattr(fm, 'related_model') and fm.related_model:
except:
pass
if fm and hasattr(fm, 'related_model')\
and fm.related_model:
rmo = fm.related_model._meta.ordering
if rmo:
rmo = rmo[0]
@ -487,13 +522,12 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
ordering = ordering + (mo, )
queryset = queryset.order_by(*ordering)
print(ordering)
# print(ordering)
except Exception as e:
logger.error(string_concat(_(
'ERRO: contrução da tupla de ordenação.'), str(e)))
elif hasattr(self, 'initial_order'):
queryset = queryset.order_by(*(self.initial_order))
'ERRO: construção da tupla de ordenação.'), str(e)))
# print(queryset.query)
if not self.request.user.is_authenticated():
return queryset
@ -748,6 +782,13 @@ class CrudDeleteView(PermissionRequiredContainerCrudMixin,
return self.list_url
class DeactivatedMixin(View):
@classmethod
def get_url_regex(cls):
return r'^dummy$'
class Crud:
BaseMixin = CrudBaseMixin
ListView = CrudListView
@ -757,10 +798,14 @@ class Crud:
DeleteView = CrudDeleteView
help_path = ''
class PublicMixin:
permission_required = []
@classonlymethod
def get_urls(cls):
def _add_base(view):
if view:
class CrudViewWithBase(cls.BaseMixin, view):
model = cls.model
help_path = cls.help_path
@ -774,18 +819,25 @@ class Crud:
CrudUpdateView = _add_base(cls.UpdateView)
CrudDeleteView = _add_base(cls.DeleteView)
cruds_base = [
(CrudListView.get_url_regex()
if CrudListView else None, CrudListView, ACTION_LIST),
(CrudCreateView.get_url_regex()
if CrudCreateView else None, CrudCreateView, ACTION_CREATE),
(CrudDetailView.get_url_regex()
if CrudDetailView else None, CrudDetailView, ACTION_DETAIL),
(CrudUpdateView.get_url_regex()
if CrudUpdateView else None, CrudUpdateView, ACTION_UPDATE),
(CrudDeleteView.get_url_regex()
if CrudDeleteView else None, CrudDeleteView, ACTION_DELETE)]
cruds = []
for crud in cruds_base:
if crud[0]:
cruds.append(crud)
return [url(regex, view.as_view(), name=view.url_name(suffix))
for regex, view, suffix in [
(CrudListView.get_url_regex(), CrudListView, ACTION_LIST),
(CrudCreateView.get_url_regex(),
CrudCreateView, ACTION_CREATE),
(CrudDetailView.get_url_regex(),
CrudDetailView, ACTION_DETAIL),
(CrudUpdateView.get_url_regex(),
CrudUpdateView, ACTION_UPDATE),
(CrudDeleteView.get_url_regex(),
CrudDeleteView, ACTION_DELETE),
]]
for regex, view, suffix in cruds]
@classonlymethod
def build(cls, _model, _help_path, _model_set=None, list_field_names=[]):
@ -817,6 +869,15 @@ class Crud:
class CrudAux(Crud):
class BaseMixin(Crud.BaseMixin):
permission_required = ('base.view_tabelas_auxiliares',)
subnav_template_name = None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['subnav_template_name'] = self.subnav_template_name
return context
@classonlymethod
def build(cls, _model, _help_path, _model_set=None, list_field_names=[]):
@ -824,9 +885,7 @@ class CrudAux(Crud):
_model, _help_path, _model_set, list_field_names)
class ModelCrudAux(ModelCrud):
class BaseMixin(ModelCrud.BaseMixin):
permission_required = ('base.view_tabelas_auxiliares',)
BaseMixin = CrudAux.BaseMixin
return ModelCrudAux
@ -838,16 +897,25 @@ class MasterDetailCrud(Crud):
@property
def list_url(self):
obj = self.crud if hasattr(self, 'crud') else self
if not obj.ListView:
return ''
return self.resolve_url(ACTION_LIST, args=(self.kwargs['pk'],))\
if self.request.user.has_perm(self.permission(RP_LIST)) else ''
@property
def create_url(self):
obj = self.crud if hasattr(self, 'crud') else self
if not obj.CreateView:
return ''
return self.resolve_url(ACTION_CREATE, args=(self.kwargs['pk'],))\
if self.request.user.has_perm(self.permission(RP_ADD)) else ''
@property
def detail_url(self):
obj = self.crud if hasattr(self, 'crud') else self
if not obj.DetailView:
return ''
pkk = self.request.GET['pkk'] if 'pkk' in self.request.GET else ''
return (super().detail_url + (('?pkk=' + pkk) if pkk else ''))\
if self.request.user.has_perm(
@ -855,6 +923,9 @@ class MasterDetailCrud(Crud):
@property
def update_url(self):
obj = self.crud if hasattr(self, 'crud') else self
if not obj.UpdateView:
return ''
pkk = self.request.GET['pkk'] if 'pkk' in self.request.GET else ''
return (super().update_url + (('?pkk=' + pkk) if pkk else ''))\
if self.request.user.has_perm(
@ -862,6 +933,9 @@ class MasterDetailCrud(Crud):
@property
def delete_url(self):
obj = self.crud if hasattr(self, 'crud') else self
if not obj.DeleteView:
return ''
return super().delete_url\
if self.request.user.has_perm(
self.permission(RP_DELETE)) else ''
@ -910,9 +984,7 @@ class MasterDetailCrud(Crud):
def get_context_data(self, **kwargs):
obj = self.crud if hasattr(self, 'crud') else self
count = self.object_list.count()
context = CrudListView.get_context_data(self, **kwargs)
context['count'] = count
parent_model = None
if '__' in obj.parent_field:
@ -1083,6 +1155,9 @@ class MasterDetailCrud(Crud):
@property
def detail_create_url(self):
obj = self.crud if hasattr(self, 'crud') else self
if not obj.CreateView:
return ''
if self.request.user.has_perm(self.permission(RP_ADD)):
parent_field = obj.parent_field.split('__')[0]
parent_object = getattr(self.object, parent_field)
@ -1122,6 +1197,7 @@ class MasterDetailCrud(Crud):
edição em cascata de MasterDetailDetail...
"""
return ''
obj = self.crud if hasattr(self, 'crud') else self
if hasattr(obj, 'parent_field'):
# parent_field = obj.parent_field.split('__')[0]
@ -1140,3 +1216,22 @@ class MasterDetailCrud(Crud):
list_field_names=list_field_names)
crud.parent_field = parent_field
return crud
class CrudBaseForListAndDetailExternalAppView(MasterDetailCrud):
CreateView, UpdateView, DeleteView = None, None, None
class BaseMixin(Crud.PublicMixin, MasterDetailCrud.BaseMixin):
@classmethod
def url_name(cls, suffix):
return '%s_parlamentar_%s' % (cls.model._meta.model_name, suffix)
def resolve_url(self, suffix, args=None):
obj = self.crud if hasattr(self, 'crud') else self
""" namespace deve ser redirecionado para app local pois
o models colocados nos cruds que herdam este Crud são de outras app
"""
return reverse('%s:%s' % (obj.namespace, self.url_name(suffix)),
args=args)

2
sapl/materia/views.py

@ -668,7 +668,7 @@ class TramitacaoCrud(MasterDetailCrud):
class BaseMixin(MasterDetailCrud.BaseMixin):
list_field_names = ['data_tramitacao', 'unidade_tramitacao_local',
'unidade_tramitacao_destino', 'status']
initial_order = '-data_tramitacao'
ordering = '-data_tramitacao',
class CreateView(MasterDetailCrud.CreateView):
form_class = TramitacaoForm

24
sapl/parlamentares/migrations/0032_frenteproxymasterdetail.py

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-30 20:09
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('parlamentares', '0031_auto_20160929_1842'),
]
operations = [
migrations.CreateModel(
name='FrenteProxyMasterDetail',
fields=[
],
options={
'proxy': True,
},
bases=('parlamentares.frente',),
),
]

29
sapl/parlamentares/migrations/0033_auto_20160930_1715.py

@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-30 20:15
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('parlamentares', '0032_frenteproxymasterdetail'),
]
operations = [
migrations.DeleteModel(
name='FrenteProxyMasterDetail',
),
migrations.CreateModel(
name='FrenteParlamentar',
fields=[
],
options={
'proxy': True,
'verbose_name': 'Frente',
'verbose_name_plural': 'Frentes',
},
bases=('parlamentares.frente',),
),
]

18
sapl/parlamentares/migrations/0034_delete_frenteparlamentar.py

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-30 21:43
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('parlamentares', '0033_auto_20160930_1715'),
]
operations = [
migrations.DeleteModel(
name='FrenteParlamentar',
),
]

5
sapl/parlamentares/urls.py

@ -23,12 +23,9 @@ urlpatterns = [
FiliacaoCrud.get_urls() + MandatoCrud.get_urls() +
ParticipacaoParlamentarCrud.get_urls() +
ProposicaoParlamentarCrud.get_urls() +
RelatoriaParlamentarCrud.get_urls()
RelatoriaParlamentarCrud.get_urls() + FrenteList.get_urls()
)),
url(r'^parlamentar/(?P<pk>\d+)/frente$',
FrenteList.as_view(), name="frent_list"),
url(r'^sistema/coligacao/',
include(ColigacaoCrud.get_urls() +
ComposicaoColigacaoCrud.get_urls())),

356
sapl/parlamentares/views.py

@ -15,11 +15,13 @@ from sapl.comissoes.models import Participacao
from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView,
CrudDeleteView, CrudDetailView, CrudListView,
CrudUpdateView, MasterDetailCrud, CrudAux,
RP_CHANGE)
RP_CHANGE, RP_DETAIL, RP_LIST, DeactivatedMixin,
CrudBaseForListAndDetailExternalAppView)
from sapl.materia.models import Proposicao, Relatoria
from sapl.parlamentares.apps import AppConfig
from sapl.utils import permissao_tb_aux, permissoes_parlamentares
from .forms import (ComposicaoColigacaoForm, FiliacaoForm, FrenteForm,
from .forms import (ComposicaoColigacaoForm, FiliacaoForm,
LegislaturaForm, ParlamentarCreateForm, ParlamentarForm)
from .models import (CargoMesa, Coligacao, ComposicaoColigacao, ComposicaoMesa,
Dependente, Filiacao, Frente, Legislatura, Mandato,
@ -27,92 +29,72 @@ from .models import (CargoMesa, Coligacao, ComposicaoColigacao, ComposicaoMesa,
SituacaoMilitar, TipoAfastamento, TipoDependente)
class FrenteList(ListView):
model = Frente
paginate_by = 10
template_name = 'parlamentares/frentes.html'
CargoMesaCrud = CrudAux.build(CargoMesa, 'cargo_mesa')
PartidoCrud = CrudAux.build(Partido, 'partidos')
SessaoLegislativaCrud = CrudAux.build(SessaoLegislativa, 'sessao_legislativa')
TipoDependenteCrud = CrudAux.build(TipoDependente, 'tipo_dependente')
NivelInstrucaoCrud = CrudAux.build(NivelInstrucao, 'nivel_instrucao')
TipoAfastamentoCrud = CrudAux.build(TipoAfastamento, 'tipo_afastamento')
TipoMilitarCrud = CrudAux.build(SituacaoMilitar, 'tipo_situa_militar')
def get_queryset(self):
return Frente.objects.filter(parlamentares__in=[self.kwargs['pk']])
FrenteCrud = CrudAux.build(Frente, 'tipo_situa_militar', list_field_names=[
'nome', 'data_criacao', 'parlamentares'])
def get_context_data(self, **kwargs):
context = super(FrenteList, self).get_context_data(**kwargs)
context['root_pk'] = self.kwargs['pk']
context['object_list'] = self.get_queryset()
return context
DependenteCrud = MasterDetailCrud.build(
Dependente, 'parlamentar', 'dependente')
class FrenteCrud(CrudAux):
class FrenteList(MasterDetailCrud):
model = Frente
is_m2m = True
parent_field = 'parlamentares'
CreateView, UpdateView, DeleteView = None, None, None
class BaseMixin(CrudAux.BaseMixin):
list_field_names = ['nome', 'data_criacao', 'parlamentares']
form_class = FrenteForm
class BaseMixin(Crud.PublicMixin, MasterDetailCrud.BaseMixin):
list_field_names = ['nome', 'data_criacao']
@classmethod
def url_name(cls, suffix):
return '%s_parlamentar_%s' % (cls.model._meta.model_name, suffix)
class RelatoriaParlamentarCrud(MasterDetailCrud):
class RelatoriaParlamentarCrud(CrudBaseForListAndDetailExternalAppView):
model = Relatoria
parent_field = 'parlamentar'
class ListView(MasterDetailCrud.ListView):
permission_required = permissoes_parlamentares()
class CreateView(MasterDetailCrud.CreateView):
permission_required = permissoes_parlamentares()
class UpdateView(MasterDetailCrud.UpdateView):
permission_required = permissoes_parlamentares()
class DeleteView(MasterDetailCrud.DeleteView):
permission_required = permissoes_parlamentares()
help_path = 'relatoria_parlamentar'
namespace = AppConfig.name
class ProposicaoParlamentarCrud(MasterDetailCrud):
class ProposicaoParlamentarCrud(CrudBaseForListAndDetailExternalAppView):
model = Proposicao
parent_field = 'autor__parlamentar'
help_path = ''
class BaseMixin(CrudBaseMixin):
list_field_names = ['tipo', 'descricao']
parent_field = 'autor__parlamentar'
namespace = AppConfig.name
class ListView(MasterDetailCrud.ListView):
permission_required = permissoes_parlamentares()
def get_context_data(self, **kwargs):
context = super(ProposicaoParlamentarCrud.ListView, self
).get_context_data(**kwargs)
context['root_pk'] = self.kwargs['pk']
return context
class ListView(CrudBaseForListAndDetailExternalAppView.ListView):
def get_queryset(self):
try:
proposicoes = Proposicao.objects.filter(
return super().get_queryset().filter(
autor__parlamentar_id=self.kwargs['pk'],
data_envio__isnull=False)
except ObjectDoesNotExist:
return []
else:
return proposicoes
class CreateView(MasterDetailCrud.CreateView):
permission_required = permissoes_parlamentares()
class UpdateView(MasterDetailCrud.UpdateView):
permission_required = permissoes_parlamentares()
class DeleteView(MasterDetailCrud.DeleteView):
permission_required = permissoes_parlamentares()
class ParticipacaoParlamentarCrud(MasterDetailCrud):
class ParticipacaoParlamentarCrud(CrudBaseForListAndDetailExternalAppView):
model = Participacao
parent_field = 'parlamentar'
help_path = ''
namespace = AppConfig.name
list_field_names = ['composicao__comissao__nome', 'cargo__nome', (
'composicao__periodo__data_inicio', 'composicao__periodo__data_fim')]
class ListView(MasterDetailCrud.ListView):
class ListView(CrudBaseForListAndDetailExternalAppView.ListView):
ordering = ('-composicao__periodo')
def get_rows(self, object_list):
"""
FIXME:
Este metodo não será necessário quando get_rows for refatorada
"""
comissoes = []
for p in object_list:
if p.cargo.nome != 'Relator':
@ -130,214 +112,75 @@ class ParticipacaoParlamentarCrud(MasterDetailCrud):
return comissoes
def get_headers(self):
return ['Comissão', 'Cargo', 'Período']
class CreateView(MasterDetailCrud.CreateView):
permission_required = permissoes_parlamentares()
class UpdateView(MasterDetailCrud.UpdateView):
permission_required = permissoes_parlamentares()
class DeleteView(MasterDetailCrud.DeleteView):
permission_required = permissoes_parlamentares()
class CargoMesaCrud(Crud):
model = CargoMesa
help_path = 'cargo_mesa'
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class PartidoCrud(Crud):
model = Partido
help_path = 'partidos'
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class SessaoLegislativaCrud(Crud):
model = SessaoLegislativa
help_path = 'sessao_legislativa'
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class TipoDependenteCrud(Crud):
model = TipoDependente
help_path = 'nivel_instrucao'
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class NivelInstrucaoCrud(Crud):
model = NivelInstrucao
help_path = 'tipo_dependente'
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class TipoAfastamentoCrud(Crud):
model = TipoAfastamento
help_path = 'tipo_afastamento'
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
return [_('Comissão'), _('Cargo'), _('Período de participação'), ]
class TipoMilitarCrud(Crud):
model = SituacaoMilitar
help_path = 'tipo_situa_militar'
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class DependenteCrud(MasterDetailCrud):
model = Dependente
parent_field = 'parlamentar'
help_path = ''
class CreateView(MasterDetailCrud.CreateView):
permission_required = permissoes_parlamentares()
class UpdateView(MasterDetailCrud.UpdateView):
permission_required = permissoes_parlamentares()
class DeleteView(MasterDetailCrud.DeleteView):
permission_required = permissoes_parlamentares()
class ColigacaoCrud(CrudAux):
model = Coligacao
help_path = 'tabelas_auxiliares#coligacao'
class ListView(MasterDetailCrud.ListView):
permission_required = permissoes_parlamentares()
class ListView(CrudAux.ListView):
ordering = ('-numero_votos', 'nome')
class DetailView(MasterDetailCrud.DetailView):
permission_required = permissoes_parlamentares()
class BaseMixin(CrudAux.BaseMixin):
subnav_template_name = 'parlamentares/subnav_coligacao.yaml'
class MandatoCrud(MasterDetailCrud):
model = Mandato
parent_field = 'parlamentar'
help_path = ''
public = [RP_DETAIL, RP_LIST]
class ListView(MasterDetailCrud.ListView):
ordering = ('-legislatura__numero')
class CreateView(MasterDetailCrud.CreateView):
permission_required = permissoes_parlamentares()
class UpdateView(MasterDetailCrud.UpdateView):
permission_required = permissoes_parlamentares()
class DeleteView(MasterDetailCrud.DeleteView):
permission_required = permissoes_parlamentares()
class ColigacaoCrud(Crud):
model = Coligacao
help_path = 'tabelas_auxiliares#coligacao'
class ListView(CrudListView):
ordering = ('-numero_votos', 'nome')
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class ComposicaoColigacaoCrud(MasterDetailCrud):
model = ComposicaoColigacao
parent_field = 'coligacao'
help_path = ''
class CreateView(MasterDetailCrud.CreateView):
form_class = ComposicaoColigacaoForm
def get_initial(self):
id = self.kwargs['pk']
return {'coligacao_id': id}
class UpdateView(MasterDetailCrud.UpdateView):
form_class = ComposicaoColigacaoForm
class BaseMixin(MasterDetailCrud.BaseMixin):
def get_initial(self):
id = self.kwargs['pk']
return {'coligacao_id': id}
def get_context_data(self, **kwargs):
context = super().get_context_data()
context['subnav_template_name'] = \
'parlamentares/subnav_coligacao.yaml'
return context
class ListView(MasterDetailCrud.ListView):
ordering = '-partido__sigla'
class BaseMixin(MasterDetailCrud.BaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class LegislaturaCrud(Crud):
class LegislaturaCrud(CrudAux):
model = Legislatura
help_path = 'tabelas_auxiliares#legislatura'
class CreateView(CrudCreateView):
form_class = LegislaturaForm
class UpdateView(CrudUpdateView):
class BaseMixin(CrudAux.BaseMixin):
form_class = LegislaturaForm
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class FiliacaoCrud(MasterDetailCrud):
model = Filiacao
parent_field = 'parlamentar'
help_path = ''
public = [RP_LIST, RP_DETAIL]
class CreateView(MasterDetailCrud.CreateView):
form_class = FiliacaoForm
permission_required = permissoes_parlamentares()
class UpdateView(MasterDetailCrud.UpdateView):
form_class = FiliacaoForm
permission_required = permissoes_parlamentares()
class DeleteView(MasterDetailCrud.DeleteView):
permission_required = permissoes_parlamentares()
class ListView(MasterDetailCrud.ListView):
class BaseMixin(MasterDetailCrud.BaseMixin):
ordering = '-data'
class ParlamentarCrud(Crud):
model = Parlamentar
public = [RP_LIST, RP_DETAIL]
class BaseMixin(Crud.BaseMixin):
form_class = ParlamentarCreateForm
ordered_list = False
list_field_names = [
'avatar_html', 'nome_parlamentar', 'filiacao_atual', 'ativo']
class DetailView(Crud.DetailView):
permission_required = []
def get_template_names(self):
return ['crud/detail.html']\
@ -353,8 +196,16 @@ class ParlamentarCrud(Crud):
def layout_key(self):
return 'ParlamentarCreate'
def form_valid(self, form):
'''
Reimplementa form_valid devido ao save de ParlamentarCreateForm
ser específico, sendo necessário isolar padrão do crud que aciona
form.save(commit=False) para registrar dados de auditoria se
o model implementá-los, bem como de container se também implement.
'''
return super(Crud.CreateView, self).form_valid(form)
class ListView(Crud.ListView):
permission_required = []
template_name = "parlamentares/parlamentares_list.html"
paginate_by = None
@ -394,19 +245,8 @@ class ParlamentarCrud(Crud):
return context
def check_permission_mesa(request):
lista_permissoes = []
cts = ContentType.objects.filter(app_label='parlamentares')
cts = cts.filter(model__icontains='mesa')
perms = list(Permission.objects.filter(content_type__in=cts))
for p in perms:
lista_permissoes.append('parlamentares.' + p.codename)
return request.user.has_perms(set(lista_permissoes))
class MesaDiretoraView(FormView):
template_name = "mesa_diretora/mesa_diretora.html"
template_name = 'parlamentares/composicaomesa_form.html'
success_url = reverse_lazy('sapl.parlamentares:mesa_diretora')
# Essa função avisa quando se pode compor uma Mesa Legislativa
@ -425,18 +265,18 @@ class MesaDiretoraView(FormView):
def get(self, request, *args, **kwargs):
if (not Legislatura.objects.exists() or
not SessaoLegislativa.objects.all()):
not SessaoLegislativa.objects.exists()):
return self.validation(request)
mesa = SessaoLegislativa.objects.filter(
legislatura=Legislatura.objects.last()).first(
legislatura=Legislatura.objects.first()).first(
).composicaomesa_set.all()
cargos_ocupados = [m.cargo for m in mesa]
cargos = CargoMesa.objects.all()
cargos_vagos = list(set(cargos) - set(cargos_ocupados))
parlamentares = Legislatura.objects.last().mandato_set.all()
parlamentares = Legislatura.objects.first().mandato_set.all()
parlamentares_ocupados = [m.parlamentar for m in mesa]
parlamentares_vagos = list(
set(
@ -446,23 +286,26 @@ class MesaDiretoraView(FormView):
return self.render_to_response(
{'legislaturas': Legislatura.objects.all(
).order_by('-numero'),
'legislatura_selecionada': Legislatura.objects.last(),
'legislatura_selecionada': Legislatura.objects.first(),
'sessoes': SessaoLegislativa.objects.filter(
legislatura=Legislatura.objects.last()),
legislatura=Legislatura.objects.first()),
'sessao_selecionada': SessaoLegislativa.objects.filter(
legislatura=Legislatura.objects.last()).first(),
legislatura=Legislatura.objects.first()).first(),
'composicao_mesa': mesa,
'parlamentares': parlamentares_vagos,
'cargos_vagos': cargos_vagos
})
def post(self, request, *args, **kwargs):
if 'Incluir' in request.POST and check_permission_mesa(request):
if (not Legislatura.objects.all() or
not SessaoLegislativa.objects.all()):
if (not Legislatura.objects.exists() or
not SessaoLegislativa.objects.exists()):
return self.validation(request)
if 'Incluir' in request.POST and request.user.has_perm(
'%s.add_%s' % (
AppConfig.label, ComposicaoMesa._meta.model_name)):
composicao = ComposicaoMesa()
composicao.sessao_legislativa = SessaoLegislativa.objects.get(
id=int(request.POST['sessao']))
@ -472,13 +315,12 @@ class MesaDiretoraView(FormView):
id=int(request.POST['cargo']))
composicao.save()
return redirect('sapl.parlamentares:mesa_diretora')
elif 'Excluir' in request.POST and check_permission_mesa(request):
messages.success(request, _(
'Parlamentar adicionado com sucesso!'))
if (not Legislatura.objects.all() or
not SessaoLegislativa.objects.all()):
return self.validation(request)
elif 'Excluir' in request.POST and request.user.has_perm(
'%s.delete_%s' % (
AppConfig.label, ComposicaoMesa._meta.model_name)):
if 'composicao_mesa' in request.POST:
ids = request.POST['composicao_mesa'].split(':')
@ -488,8 +330,12 @@ class MesaDiretoraView(FormView):
cargo_id=int(ids[1])
)
composicao.delete()
return redirect('sapl.parlamentares:mesa_diretora')
messages.success(request, _(
'Parlamentar excluido com sucesso!'))
else:
messages.error(request, _(
'Selecione um parlamentar para ser excluido!'))
mesa = ComposicaoMesa.objects.filter(
sessao_legislativa=request.POST['sessao'])
@ -504,6 +350,13 @@ class MesaDiretoraView(FormView):
set(
[p.parlamentar for p in parlamentares]) - set(
parlamentares_ocupados))
sessao_selecionada = SessaoLegislativa.objects.get(
id=int(request.POST['sessao']))
if str(sessao_selecionada.legislatura_id) != int(
request.POST['legislatura']):
sessao_selecionada = SessaoLegislativa.objects.filter(
legislatura=Legislatura.objects.first()).first()
return self.render_to_response(
{'legislaturas': Legislatura.objects.all(
).order_by('-numero'),
@ -511,8 +364,7 @@ class MesaDiretoraView(FormView):
id=int(request.POST['legislatura'])),
'sessoes': SessaoLegislativa.objects.filter(
legislatura_id=int(request.POST['legislatura'])),
'sessao_selecionada': SessaoLegislativa.objects.get(
id=int(request.POST['sessao'])),
'sessao_selecionada': sessao_selecionada,
'composicao_mesa': mesa,
'parlamentares': parlamentares_vagos,
'cargos_vagos': cargos_vagos

2
sapl/templates/crud/detail.html

@ -7,7 +7,7 @@
{% block actions %}
<div class="actions btn-group btn-group-sm" role="group">
{% if view.list_url %}
<a href="{{ view.list_url }}?list" class="btn btn-default">{% trans 'Listar' %} {{view.verbose_name_plural}}</a>
<a href="{{ view.list_url }}" class="btn btn-default">{% trans 'Listar' %} {{view.verbose_name_plural}}</a>
{% endif %}
{% if view.create_url %}
<a href="{{ view.create_url }}" class="btn btn-default">

4
sapl/templates/crud/detail_detail.html

@ -7,7 +7,7 @@
{% block actions %}
<div class="actions btn-group btn-group-sm" role="group">
{% if view.detail_list_url %}
<a href="{{ view.detail_list_url }}?list" class="btn btn-default">{% trans 'Listar' %} {{view.verbose_name_plural}}</a>
<a href="{{ view.detail_list_url }}" class="btn btn-default">{% trans 'Listar' %} {{view.verbose_name_plural}}</a>
{% endif %}
{% if view.detail_create_url %}
<a href="{{ view.detail_create_url }}" class="btn btn-default">
@ -21,7 +21,7 @@
<a href="{{ view.update_url }}" class="btn btn-default">{% trans 'Editar' %}</a>
{% endif %}
{% if view.delete_url %}
<a href="{{ view.delete_url }}" class="btn btn-default btn-excluir">{% trans 'Excluir' %}</a>
<a href="{{ view.delete_url }}" class="btn btn-danger btn-excluir">{% trans 'Excluir' %}</a>
{% endif %}
</div>
{% endif %}

14
sapl/templates/crud/list.html

@ -34,14 +34,20 @@
<tr>
{% for name in headers %}
<th>
<a title="{% trans 'Clique para alterar a ordem a listagem'%}" href="?o={% if 'o' not in request.GET and view.initial_order.0 != '-' or 'o' not in request.GET and not view.initial_order and forloop.counter == 1 or 'o' in request.GET and forloop.counter|safe == request.GET.o %}-{%endif%}{{forloop.counter}}{{ordering_url}}">{{ name }}
{% if 'o' not in request.GET and view.initial_order and view.initial_order.0 != '-' or 'o' not in request.GET and not view.initial_order and forloop.counter == 1 or 'o' in request.GET and forloop.counter|safe == request.GET.o %}
{% if view.ordered_list %}
<a title="{% trans 'Clique para alterar a ordem a listagem'%}" href="?o={% if 'o' not in request.GET and forloop.counter == 1 or 'o' in request.GET and forloop.counter|safe == request.GET.o %}-{%endif%}{{forloop.counter}}{{ordering_url}}">
{{ name }}
{% if 'o' in request.GET or not view.ordering %}
{% if 'o' not in request.GET and forloop.counter == 1 or 'o' in request.GET and forloop.counter|safe == request.GET.o %}
<span class="caret top" title="{% trans 'Listado na Ordem Ascendente'%}"></span>
{% elif 'o' not in request.GET and view.initial_order and view.initial_order.0 == '-' or 'o' in request.GET and forloop.counter == request.GET.o|str2intabs %}
{% elif 'o' in request.GET and forloop.counter == request.GET.o|str2intabs %}
<span class="caret" title="{% trans 'Listado na Ordem Descendente'%}"></span>
{%endif%}
{%endif%}
</a>
{% else %}
{{ name }}
{% endif %}
</th>
{% endfor %}
</tr>

10
sapl/templates/parlamentares/coligacao_detail.html

@ -1,10 +0,0 @@
{% extends "crud/detail.html" %}
{% load i18n %}
{% block actions %}
<div class="actions btn-group pull-right" role="group">
<a href="{% url 'sapl.parlamentares:composicaocoligacao_list' object.pk %}" class="btn btn-default">{% trans 'Ver Composição' %}</a>
<a href="{{ view.update_url }}" class="btn btn-default">{% trans 'Editar' %}</a>
<a href="{{ view.delete_url }}" class="btn btn-default">{% trans 'Excluir' %}</a>
</div>
{% endblock actions %}

4
sapl/templates/mesa_diretora/mesa_diretora.html → sapl/templates/parlamentares/composicaomesa_form.html

@ -48,13 +48,13 @@
<div class="col-md-4" align="center">
<br /><br />
{% if cargos_vagos %}
{% if perms.parlamentares.add_cargomesa or perms.parlamentares.add_composicaomesa %}
{% if perms.parlamentares.add_cargomesa%}
<input type="submit" name="Incluir" Value="Incluir" class="btn btn-primary" />
{% endif %}
{% endif %}
<br />
<br />
{% if perms.parlamentares.add_cargomesa or perms.parlamentares.add_composicaomesa %}
{% if perms.parlamentares.add_composicaomesa %}
<input type="submit" name="Excluir" Value="Excluir" class="btn btn-danger" />
{% endif %}
</div>

21
sapl/templates/parlamentares/frentes.html

@ -1,21 +0,0 @@
{% extends "crud/list.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block base_content %}
{% if object_list|length == 0 %}
<p>Nenhuma frente encontrada.</p>
{% else %}
<table class="table table-striped table-hover">
<thead>
<tr><th>Frentes</th></tr>
</thead>
<tbody>
{% for frente in object_list %}
<tr><td><a href="{% url 'sapl.parlamentares:frente_detail' frente.pk %}">{{ frente.nome }}</a></td></tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% include "paginacao.html" %}
{% endblock %}

8
sapl/templates/parlamentares/subnav.yaml

@ -8,10 +8,10 @@
- title: {% trans 'Dependentes' %}
url: dependente_list
- title: {% trans 'Comissões' %}
url: participacao_list
url: participacao_parlamentar_list
- title: {% trans 'Proposições' %}
url: proposicao_list
url: proposicao_parlamentar_list
- title: {% trans 'Relatorias' %}
url: relatoria_list
url: relatoria_parlamentar_list
- title: {% trans 'Frentes' %}
url: frent_list
url: frente_parlamentar_list

5
sapl/templates/parlamentares/subnav_coligacao.yaml

@ -0,0 +1,5 @@
{% load i18n %}
- title: {% trans 'Início' %}
url: coligacao_detail
- title: {% trans 'Composição da Coligação' %}
url: composicaocoligacao_list

25
scripts/inicializa_grupos_autorizacoes.py

@ -1,24 +1,33 @@
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sapl.settings")
django.setup()
if __name__ == '__main__':
from django.apps import apps
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
def cria_ou_reseta_grupo(nome):
grupo = Group.objects.get_or_create(name=nome)[0]
for p in list(grupo.permissions.all()):
grupo.permissions.remove(p)
return grupo
def cria_usuario(nome, grupo):
nome_usuario = nome
usuario = get_user_model().objects.get_or_create(username=nome_usuario)[0]
usuario = get_user_model().objects.get_or_create(
username=nome_usuario)[0]
usuario.set_password('interlegis')
usuario.save()
grupo.user_set.add(usuario)
def cria_grupos_permissoes():
nomes_apps = ['base', 'parlamentares', 'comissoes',
@ -101,8 +110,10 @@ def cria_grupos_permissoes():
# Autor
perms_autor = []
perms_autor.append(Permission.objects.get(name='Can add Proposição'))
perms_autor.append(Permission.objects.get(name='Can change Proposição'))
perms_autor.append(Permission.objects.get(name='Can delete Proposição'))
perms_autor.append(
Permission.objects.get(name='Can change Proposição'))
perms_autor.append(
Permission.objects.get(name='Can delete Proposição'))
# Configura Permissoes Autor
grupo = cria_ou_reseta_grupo('Autor')
@ -112,6 +123,4 @@ def cria_grupos_permissoes():
nome_usuario = 'operador_autor'
cria_usuario(nome_usuario, grupo)
if __name__ == '__main__':
cria_grupos_permissoes()

Loading…
Cancel
Save