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. 37
      scripts/inicializa_grupos_autorizacoes.py

8
sapl/base/templatetags/menus.py

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

2
sapl/comissoes/views.py

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

3
sapl/crispy_layout_mixin.py

@ -149,6 +149,9 @@ class CrispyLayoutFormMixin:
This base implementation returns the field names This base implementation returns the field names
in the first fieldset of the layout. 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:] rows = self.get_layout()[0][1:]
return [fieldname for row in rows for fieldname, __ in row] 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.utils.translation import ugettext_lazy as _
from django.views.generic import (CreateView, DeleteView, DetailView, ListView, from django.views.generic import (CreateView, DeleteView, DetailView, ListView,
UpdateView) UpdateView)
from django.views.generic.base import ContextMixin from django.views.generic.base import ContextMixin, View
from django.views.generic.list import MultipleObjectMixin from django.views.generic.list import MultipleObjectMixin
from sapl.crispy_layout_mixin import CrispyLayoutFormMixin, get_field_display from sapl.crispy_layout_mixin import CrispyLayoutFormMixin, get_field_display
@ -79,6 +79,7 @@ def make_pagination(index, num_pages):
""" """
variáveis do crud: variáveis do crud:
help_path
container_field container_field
container_field_set container_field_set
is_m2m is_m2m
@ -90,10 +91,9 @@ variáveis do crud:
permission_required -> este atributo ser vazio não nulo torna a view publ permission_required -> este atributo ser vazio não nulo torna a view publ
layout_key_set layout_key_set
layout_key layout_key
ordered_list = False desativa os clicks e controles de ord da listagem
parent_field = parentesco reverso separado por '__' parent_field = parentesco reverso separado por '__'
initial_order = deve ser um elemento de list_field_names namespace
FIXME: as setas indicativas de ordem em crud/list.html
não está se comportando como esperado para initial_order descrescente
""" """
@ -214,8 +214,11 @@ class CrudBaseMixin(CrispyLayoutFormMixin):
self.model_name_set = getattr( self.model_name_set = getattr(
obj.model, obj.model_set).field.model._meta.model_name obj.model, obj.model_set).field.model._meta.model_name
if hasattr(self, 'permission_required') and\ if hasattr(self, 'permission_required') and self.permission_required:
self.permission_required: if hasattr(obj, 'public'):
self.permission_required = list(
set(self.permission_required) - set(obj.public))
self.permission_required = tuple(( self.permission_required = tuple((
self.permission(pr) for pr in self.permission_required)) self.permission(pr) for pr in self.permission_required))
@ -225,8 +228,8 @@ class CrudBaseMixin(CrispyLayoutFormMixin):
def url_name_set(self, suffix): def url_name_set(self, suffix):
obj = self.crud if hasattr(self, 'crud') else self obj = self.crud if hasattr(self, 'crud') else self
return '%s_%s' % (getattr( return '%s_%s' % (getattr(obj.model, obj.model_set
obj.model, obj.model_set).field.model._meta.model_name, suffix) ).field.model._meta.model_name, suffix)
def permission(self, rad): def permission(self, rad):
return '%s%s%s' % (self.app_label if rad.endswith('_') else '', 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)), return reverse('%s:%s' % (namespace, self.url_name_set(suffix)),
args=args) args=args)
@property
def ordered_list(self):
return True
@property @property
def list_url(self): def list_url(self):
obj = self.crud if hasattr(self, 'crud') else 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. para junção de fields via tuplas.
list_field_names pode ser construido como list_field_names pode ser construido como
list_field_names=('nome', 'endereco', ('telefone', sexo'), 'dat_nasc') 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 = [] r = []
for fieldname in self.list_field_names: for fieldname in self.list_field_names:
if isinstance(fieldname, tuple): if not isinstance(fieldname, tuple):
s = [force_text(self.model._meta.get_field( fieldname = fieldname,
fn).verbose_name) for fn in 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) s = ' / '.join(s)
r.append(s) r.append(s)
else:
r.append(
self.model._meta.get_field(fieldname).verbose_name)
return r return r
def _as_row(self, obj): 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 = [] r = []
for i, name in enumerate(self.list_field_names): for i, name in enumerate(self.list_field_names):
url = self.resolve_url( url = self.resolve_url(
@ -420,6 +444,8 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
del qr['page'] del qr['page']
context['filter_url'] = ( context['filter_url'] = (
'&' + qr.urlencode()) if len(qr) > 0 else '' '&' + qr.urlencode()) if len(qr) > 0 else ''
if self.ordered_list:
if 'o' in qr: if 'o' in qr:
del qr['o'] del qr['o']
context['ordering_url'] = ( context['ordering_url'] = (
@ -447,6 +473,7 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
if q: if q:
queryset = queryset.filter(q) queryset = queryset.filter(q)
if self.ordered_list:
list_field_names = self.list_field_names list_field_names = self.list_field_names
o = '1' o = '1'
desc = '' desc = ''
@ -454,7 +481,8 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
o = self.request.GET['o'] o = self.request.GET['o']
desc = '-' if o.startswith('-') else '' 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: try:
fields_for_ordering = list_field_names[ fields_for_ordering = list_field_names[
(abs(int(o)) - 1) % len(list_field_names)] (abs(int(o)) - 1) % len(list_field_names)]
@ -465,8 +493,15 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
ordering = () ordering = ()
model = self.model model = self.model
for fo in fields_for_ordering: for fo in fields_for_ordering:
fm = None
try:
fm = model._meta.get_field(fo) 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 rmo = fm.related_model._meta.ordering
if rmo: if rmo:
rmo = rmo[0] rmo = rmo[0]
@ -487,13 +522,12 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView):
ordering = ordering + (mo, ) ordering = ordering + (mo, )
queryset = queryset.order_by(*ordering) queryset = queryset.order_by(*ordering)
print(ordering) # print(ordering)
except Exception as e: except Exception as e:
logger.error(string_concat(_( logger.error(string_concat(_(
'ERRO: contrução da tupla de ordenação.'), str(e))) 'ERRO: construção da tupla de ordenação.'), str(e)))
elif hasattr(self, 'initial_order'):
queryset = queryset.order_by(*(self.initial_order))
# print(queryset.query)
if not self.request.user.is_authenticated(): if not self.request.user.is_authenticated():
return queryset return queryset
@ -748,6 +782,13 @@ class CrudDeleteView(PermissionRequiredContainerCrudMixin,
return self.list_url return self.list_url
class DeactivatedMixin(View):
@classmethod
def get_url_regex(cls):
return r'^dummy$'
class Crud: class Crud:
BaseMixin = CrudBaseMixin BaseMixin = CrudBaseMixin
ListView = CrudListView ListView = CrudListView
@ -757,10 +798,14 @@ class Crud:
DeleteView = CrudDeleteView DeleteView = CrudDeleteView
help_path = '' help_path = ''
class PublicMixin:
permission_required = []
@classonlymethod @classonlymethod
def get_urls(cls): def get_urls(cls):
def _add_base(view): def _add_base(view):
if view:
class CrudViewWithBase(cls.BaseMixin, view): class CrudViewWithBase(cls.BaseMixin, view):
model = cls.model model = cls.model
help_path = cls.help_path help_path = cls.help_path
@ -774,18 +819,25 @@ class Crud:
CrudUpdateView = _add_base(cls.UpdateView) CrudUpdateView = _add_base(cls.UpdateView)
CrudDeleteView = _add_base(cls.DeleteView) 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)) return [url(regex, view.as_view(), name=view.url_name(suffix))
for regex, view, suffix in [ for regex, view, suffix in cruds]
(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),
]]
@classonlymethod @classonlymethod
def build(cls, _model, _help_path, _model_set=None, list_field_names=[]): def build(cls, _model, _help_path, _model_set=None, list_field_names=[]):
@ -817,6 +869,15 @@ class Crud:
class CrudAux(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 @classonlymethod
def build(cls, _model, _help_path, _model_set=None, list_field_names=[]): 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) _model, _help_path, _model_set, list_field_names)
class ModelCrudAux(ModelCrud): class ModelCrudAux(ModelCrud):
BaseMixin = CrudAux.BaseMixin
class BaseMixin(ModelCrud.BaseMixin):
permission_required = ('base.view_tabelas_auxiliares',)
return ModelCrudAux return ModelCrudAux
@ -838,16 +897,25 @@ class MasterDetailCrud(Crud):
@property @property
def list_url(self): 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'],))\ return self.resolve_url(ACTION_LIST, args=(self.kwargs['pk'],))\
if self.request.user.has_perm(self.permission(RP_LIST)) else '' if self.request.user.has_perm(self.permission(RP_LIST)) else ''
@property @property
def create_url(self): 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'],))\ return self.resolve_url(ACTION_CREATE, args=(self.kwargs['pk'],))\
if self.request.user.has_perm(self.permission(RP_ADD)) else '' if self.request.user.has_perm(self.permission(RP_ADD)) else ''
@property @property
def detail_url(self): 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 '' pkk = self.request.GET['pkk'] if 'pkk' in self.request.GET else ''
return (super().detail_url + (('?pkk=' + pkk) if pkk else ''))\ return (super().detail_url + (('?pkk=' + pkk) if pkk else ''))\
if self.request.user.has_perm( if self.request.user.has_perm(
@ -855,6 +923,9 @@ class MasterDetailCrud(Crud):
@property @property
def update_url(self): 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 '' pkk = self.request.GET['pkk'] if 'pkk' in self.request.GET else ''
return (super().update_url + (('?pkk=' + pkk) if pkk else ''))\ return (super().update_url + (('?pkk=' + pkk) if pkk else ''))\
if self.request.user.has_perm( if self.request.user.has_perm(
@ -862,6 +933,9 @@ class MasterDetailCrud(Crud):
@property @property
def delete_url(self): def delete_url(self):
obj = self.crud if hasattr(self, 'crud') else self
if not obj.DeleteView:
return ''
return super().delete_url\ return super().delete_url\
if self.request.user.has_perm( if self.request.user.has_perm(
self.permission(RP_DELETE)) else '' self.permission(RP_DELETE)) else ''
@ -910,9 +984,7 @@ class MasterDetailCrud(Crud):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
obj = self.crud if hasattr(self, 'crud') else self obj = self.crud if hasattr(self, 'crud') else self
count = self.object_list.count()
context = CrudListView.get_context_data(self, **kwargs) context = CrudListView.get_context_data(self, **kwargs)
context['count'] = count
parent_model = None parent_model = None
if '__' in obj.parent_field: if '__' in obj.parent_field:
@ -1083,6 +1155,9 @@ class MasterDetailCrud(Crud):
@property @property
def detail_create_url(self): def detail_create_url(self):
obj = self.crud if hasattr(self, 'crud') else 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)): if self.request.user.has_perm(self.permission(RP_ADD)):
parent_field = obj.parent_field.split('__')[0] parent_field = obj.parent_field.split('__')[0]
parent_object = getattr(self.object, parent_field) parent_object = getattr(self.object, parent_field)
@ -1122,6 +1197,7 @@ class MasterDetailCrud(Crud):
edição em cascata de MasterDetailDetail... edição em cascata de MasterDetailDetail...
""" """
return '' return ''
obj = self.crud if hasattr(self, 'crud') else self obj = self.crud if hasattr(self, 'crud') else self
if hasattr(obj, 'parent_field'): if hasattr(obj, 'parent_field'):
# parent_field = obj.parent_field.split('__')[0] # parent_field = obj.parent_field.split('__')[0]
@ -1140,3 +1216,22 @@ class MasterDetailCrud(Crud):
list_field_names=list_field_names) list_field_names=list_field_names)
crud.parent_field = parent_field crud.parent_field = parent_field
return crud 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): class BaseMixin(MasterDetailCrud.BaseMixin):
list_field_names = ['data_tramitacao', 'unidade_tramitacao_local', list_field_names = ['data_tramitacao', 'unidade_tramitacao_local',
'unidade_tramitacao_destino', 'status'] 'unidade_tramitacao_destino', 'status']
initial_order = '-data_tramitacao' ordering = '-data_tramitacao',
class CreateView(MasterDetailCrud.CreateView): class CreateView(MasterDetailCrud.CreateView):
form_class = TramitacaoForm 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() + FiliacaoCrud.get_urls() + MandatoCrud.get_urls() +
ParticipacaoParlamentarCrud.get_urls() + ParticipacaoParlamentarCrud.get_urls() +
ProposicaoParlamentarCrud.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/', url(r'^sistema/coligacao/',
include(ColigacaoCrud.get_urls() + include(ColigacaoCrud.get_urls() +
ComposicaoColigacaoCrud.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, from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView,
CrudDeleteView, CrudDetailView, CrudListView, CrudDeleteView, CrudDetailView, CrudListView,
CrudUpdateView, MasterDetailCrud, CrudAux, CrudUpdateView, MasterDetailCrud, CrudAux,
RP_CHANGE) RP_CHANGE, RP_DETAIL, RP_LIST, DeactivatedMixin,
CrudBaseForListAndDetailExternalAppView)
from sapl.materia.models import Proposicao, Relatoria from sapl.materia.models import Proposicao, Relatoria
from sapl.parlamentares.apps import AppConfig
from sapl.utils import permissao_tb_aux, permissoes_parlamentares from sapl.utils import permissao_tb_aux, permissoes_parlamentares
from .forms import (ComposicaoColigacaoForm, FiliacaoForm, FrenteForm, from .forms import (ComposicaoColigacaoForm, FiliacaoForm,
LegislaturaForm, ParlamentarCreateForm, ParlamentarForm) LegislaturaForm, ParlamentarCreateForm, ParlamentarForm)
from .models import (CargoMesa, Coligacao, ComposicaoColigacao, ComposicaoMesa, from .models import (CargoMesa, Coligacao, ComposicaoColigacao, ComposicaoMesa,
Dependente, Filiacao, Frente, Legislatura, Mandato, Dependente, Filiacao, Frente, Legislatura, Mandato,
@ -27,92 +29,72 @@ from .models import (CargoMesa, Coligacao, ComposicaoColigacao, ComposicaoMesa,
SituacaoMilitar, TipoAfastamento, TipoDependente) SituacaoMilitar, TipoAfastamento, TipoDependente)
class FrenteList(ListView): CargoMesaCrud = CrudAux.build(CargoMesa, 'cargo_mesa')
model = Frente PartidoCrud = CrudAux.build(Partido, 'partidos')
paginate_by = 10 SessaoLegislativaCrud = CrudAux.build(SessaoLegislativa, 'sessao_legislativa')
template_name = 'parlamentares/frentes.html' 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): FrenteCrud = CrudAux.build(Frente, 'tipo_situa_militar', list_field_names=[
return Frente.objects.filter(parlamentares__in=[self.kwargs['pk']]) 'nome', 'data_criacao', 'parlamentares'])
def get_context_data(self, **kwargs): DependenteCrud = MasterDetailCrud.build(
context = super(FrenteList, self).get_context_data(**kwargs) Dependente, 'parlamentar', 'dependente')
context['root_pk'] = self.kwargs['pk']
context['object_list'] = self.get_queryset()
return context
class FrenteCrud(CrudAux): class FrenteList(MasterDetailCrud):
model = Frente model = Frente
is_m2m = True
parent_field = 'parlamentares'
CreateView, UpdateView, DeleteView = None, None, None
class BaseMixin(CrudAux.BaseMixin): class BaseMixin(Crud.PublicMixin, MasterDetailCrud.BaseMixin):
list_field_names = ['nome', 'data_criacao', 'parlamentares'] list_field_names = ['nome', 'data_criacao']
form_class = FrenteForm
@classmethod
def url_name(cls, suffix):
return '%s_parlamentar_%s' % (cls.model._meta.model_name, suffix)
class RelatoriaParlamentarCrud(MasterDetailCrud): class RelatoriaParlamentarCrud(CrudBaseForListAndDetailExternalAppView):
model = Relatoria model = Relatoria
parent_field = 'parlamentar' parent_field = 'parlamentar'
help_path = 'relatoria_parlamentar'
class ListView(MasterDetailCrud.ListView): namespace = AppConfig.name
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()
class ProposicaoParlamentarCrud(MasterDetailCrud): class ProposicaoParlamentarCrud(CrudBaseForListAndDetailExternalAppView):
model = Proposicao model = Proposicao
parent_field = 'autor__parlamentar'
help_path = ''
class BaseMixin(CrudBaseMixin):
list_field_names = ['tipo', 'descricao'] list_field_names = ['tipo', 'descricao']
parent_field = 'autor__parlamentar'
namespace = AppConfig.name
class ListView(MasterDetailCrud.ListView): class ListView(CrudBaseForListAndDetailExternalAppView.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
def get_queryset(self): def get_queryset(self):
try: return super().get_queryset().filter(
proposicoes = Proposicao.objects.filter(
autor__parlamentar_id=self.kwargs['pk'], autor__parlamentar_id=self.kwargs['pk'],
data_envio__isnull=False) data_envio__isnull=False)
except ObjectDoesNotExist:
return []
else:
return proposicoes
class CreateView(MasterDetailCrud.CreateView):
permission_required = permissoes_parlamentares()
class UpdateView(MasterDetailCrud.UpdateView): class ParticipacaoParlamentarCrud(CrudBaseForListAndDetailExternalAppView):
permission_required = permissoes_parlamentares()
class DeleteView(MasterDetailCrud.DeleteView):
permission_required = permissoes_parlamentares()
class ParticipacaoParlamentarCrud(MasterDetailCrud):
model = Participacao model = Participacao
parent_field = 'parlamentar' 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') ordering = ('-composicao__periodo')
def get_rows(self, object_list): def get_rows(self, object_list):
"""
FIXME:
Este metodo não será necessário quando get_rows for refatorada
"""
comissoes = [] comissoes = []
for p in object_list: for p in object_list:
if p.cargo.nome != 'Relator': if p.cargo.nome != 'Relator':
@ -130,214 +112,75 @@ class ParticipacaoParlamentarCrud(MasterDetailCrud):
return comissoes return comissoes
def get_headers(self): def get_headers(self):
return ['Comissão', 'Cargo', 'Período'] return [_('Comissão'), _('Cargo'), _('Período de participação'), ]
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)
class TipoMilitarCrud(Crud):
model = SituacaoMilitar
help_path = 'tipo_situa_militar'
class BaseMixin(CrudBaseMixin): class ColigacaoCrud(CrudAux):
model = Coligacao
def has_permission(self): help_path = 'tabelas_auxiliares#coligacao'
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 ListView(MasterDetailCrud.ListView): class ListView(CrudAux.ListView):
permission_required = permissoes_parlamentares() ordering = ('-numero_votos', 'nome')
class DetailView(MasterDetailCrud.DetailView): class BaseMixin(CrudAux.BaseMixin):
permission_required = permissoes_parlamentares() subnav_template_name = 'parlamentares/subnav_coligacao.yaml'
class MandatoCrud(MasterDetailCrud): class MandatoCrud(MasterDetailCrud):
model = Mandato model = Mandato
parent_field = 'parlamentar' parent_field = 'parlamentar'
help_path = '' public = [RP_DETAIL, RP_LIST]
class ListView(MasterDetailCrud.ListView): class ListView(MasterDetailCrud.ListView):
ordering = ('-legislatura__numero') 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): class ComposicaoColigacaoCrud(MasterDetailCrud):
model = ComposicaoColigacao model = ComposicaoColigacao
parent_field = 'coligacao' parent_field = 'coligacao'
help_path = '' help_path = ''
class CreateView(MasterDetailCrud.CreateView): class BaseMixin(MasterDetailCrud.BaseMixin):
form_class = ComposicaoColigacaoForm
def get_initial(self):
id = self.kwargs['pk']
return {'coligacao_id': id}
class UpdateView(MasterDetailCrud.UpdateView):
form_class = ComposicaoColigacaoForm
def get_initial(self): def get_context_data(self, **kwargs):
id = self.kwargs['pk'] context = super().get_context_data()
return {'coligacao_id': id} context['subnav_template_name'] = \
'parlamentares/subnav_coligacao.yaml'
return context
class ListView(MasterDetailCrud.ListView): class ListView(MasterDetailCrud.ListView):
ordering = '-partido__sigla' ordering = '-partido__sigla'
class BaseMixin(MasterDetailCrud.BaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class LegislaturaCrud(CrudAux):
class LegislaturaCrud(Crud):
model = Legislatura model = Legislatura
help_path = 'tabelas_auxiliares#legislatura' help_path = 'tabelas_auxiliares#legislatura'
class CreateView(CrudCreateView): class BaseMixin(CrudAux.BaseMixin):
form_class = LegislaturaForm
class UpdateView(CrudUpdateView):
form_class = LegislaturaForm form_class = LegislaturaForm
class BaseMixin(CrudBaseMixin):
def has_permission(self):
return permissao_tb_aux(self)
class FiliacaoCrud(MasterDetailCrud): class FiliacaoCrud(MasterDetailCrud):
model = Filiacao model = Filiacao
parent_field = 'parlamentar' parent_field = 'parlamentar'
help_path = '' help_path = ''
public = [RP_LIST, RP_DETAIL]
class CreateView(MasterDetailCrud.CreateView): class BaseMixin(MasterDetailCrud.BaseMixin):
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):
ordering = '-data' ordering = '-data'
class ParlamentarCrud(Crud): class ParlamentarCrud(Crud):
model = Parlamentar model = Parlamentar
public = [RP_LIST, RP_DETAIL]
class BaseMixin(Crud.BaseMixin): class BaseMixin(Crud.BaseMixin):
form_class = ParlamentarCreateForm form_class = ParlamentarCreateForm
ordered_list = False
list_field_names = [ list_field_names = [
'avatar_html', 'nome_parlamentar', 'filiacao_atual', 'ativo'] 'avatar_html', 'nome_parlamentar', 'filiacao_atual', 'ativo']
class DetailView(Crud.DetailView): class DetailView(Crud.DetailView):
permission_required = []
def get_template_names(self): def get_template_names(self):
return ['crud/detail.html']\ return ['crud/detail.html']\
@ -353,8 +196,16 @@ class ParlamentarCrud(Crud):
def layout_key(self): def layout_key(self):
return 'ParlamentarCreate' 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): class ListView(Crud.ListView):
permission_required = []
template_name = "parlamentares/parlamentares_list.html" template_name = "parlamentares/parlamentares_list.html"
paginate_by = None paginate_by = None
@ -394,19 +245,8 @@ class ParlamentarCrud(Crud):
return context 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): class MesaDiretoraView(FormView):
template_name = "mesa_diretora/mesa_diretora.html" template_name = 'parlamentares/composicaomesa_form.html'
success_url = reverse_lazy('sapl.parlamentares:mesa_diretora') success_url = reverse_lazy('sapl.parlamentares:mesa_diretora')
# Essa função avisa quando se pode compor uma Mesa Legislativa # Essa função avisa quando se pode compor uma Mesa Legislativa
@ -425,18 +265,18 @@ class MesaDiretoraView(FormView):
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
if (not Legislatura.objects.exists() or if (not Legislatura.objects.exists() or
not SessaoLegislativa.objects.all()): not SessaoLegislativa.objects.exists()):
return self.validation(request) return self.validation(request)
mesa = SessaoLegislativa.objects.filter( mesa = SessaoLegislativa.objects.filter(
legislatura=Legislatura.objects.last()).first( legislatura=Legislatura.objects.first()).first(
).composicaomesa_set.all() ).composicaomesa_set.all()
cargos_ocupados = [m.cargo for m in mesa] cargos_ocupados = [m.cargo for m in mesa]
cargos = CargoMesa.objects.all() cargos = CargoMesa.objects.all()
cargos_vagos = list(set(cargos) - set(cargos_ocupados)) 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_ocupados = [m.parlamentar for m in mesa]
parlamentares_vagos = list( parlamentares_vagos = list(
set( set(
@ -446,23 +286,26 @@ class MesaDiretoraView(FormView):
return self.render_to_response( return self.render_to_response(
{'legislaturas': Legislatura.objects.all( {'legislaturas': Legislatura.objects.all(
).order_by('-numero'), ).order_by('-numero'),
'legislatura_selecionada': Legislatura.objects.last(), 'legislatura_selecionada': Legislatura.objects.first(),
'sessoes': SessaoLegislativa.objects.filter( 'sessoes': SessaoLegislativa.objects.filter(
legislatura=Legislatura.objects.last()), legislatura=Legislatura.objects.first()),
'sessao_selecionada': SessaoLegislativa.objects.filter( 'sessao_selecionada': SessaoLegislativa.objects.filter(
legislatura=Legislatura.objects.last()).first(), legislatura=Legislatura.objects.first()).first(),
'composicao_mesa': mesa, 'composicao_mesa': mesa,
'parlamentares': parlamentares_vagos, 'parlamentares': parlamentares_vagos,
'cargos_vagos': cargos_vagos 'cargos_vagos': cargos_vagos
}) })
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
if 'Incluir' in request.POST and check_permission_mesa(request):
if (not Legislatura.objects.all() or if (not Legislatura.objects.exists() or
not SessaoLegislativa.objects.all()): not SessaoLegislativa.objects.exists()):
return self.validation(request) 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 = ComposicaoMesa()
composicao.sessao_legislativa = SessaoLegislativa.objects.get( composicao.sessao_legislativa = SessaoLegislativa.objects.get(
id=int(request.POST['sessao'])) id=int(request.POST['sessao']))
@ -472,13 +315,12 @@ class MesaDiretoraView(FormView):
id=int(request.POST['cargo'])) id=int(request.POST['cargo']))
composicao.save() composicao.save()
return redirect('sapl.parlamentares:mesa_diretora') messages.success(request, _(
'Parlamentar adicionado com sucesso!'))
elif 'Excluir' in request.POST and check_permission_mesa(request):
if (not Legislatura.objects.all() or elif 'Excluir' in request.POST and request.user.has_perm(
not SessaoLegislativa.objects.all()): '%s.delete_%s' % (
return self.validation(request) AppConfig.label, ComposicaoMesa._meta.model_name)):
if 'composicao_mesa' in request.POST: if 'composicao_mesa' in request.POST:
ids = request.POST['composicao_mesa'].split(':') ids = request.POST['composicao_mesa'].split(':')
@ -488,8 +330,12 @@ class MesaDiretoraView(FormView):
cargo_id=int(ids[1]) cargo_id=int(ids[1])
) )
composicao.delete() composicao.delete()
return redirect('sapl.parlamentares:mesa_diretora') messages.success(request, _(
'Parlamentar excluido com sucesso!'))
else: else:
messages.error(request, _(
'Selecione um parlamentar para ser excluido!'))
mesa = ComposicaoMesa.objects.filter( mesa = ComposicaoMesa.objects.filter(
sessao_legislativa=request.POST['sessao']) sessao_legislativa=request.POST['sessao'])
@ -504,6 +350,13 @@ class MesaDiretoraView(FormView):
set( set(
[p.parlamentar for p in parlamentares]) - set( [p.parlamentar for p in parlamentares]) - set(
parlamentares_ocupados)) 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( return self.render_to_response(
{'legislaturas': Legislatura.objects.all( {'legislaturas': Legislatura.objects.all(
).order_by('-numero'), ).order_by('-numero'),
@ -511,8 +364,7 @@ class MesaDiretoraView(FormView):
id=int(request.POST['legislatura'])), id=int(request.POST['legislatura'])),
'sessoes': SessaoLegislativa.objects.filter( 'sessoes': SessaoLegislativa.objects.filter(
legislatura_id=int(request.POST['legislatura'])), legislatura_id=int(request.POST['legislatura'])),
'sessao_selecionada': SessaoLegislativa.objects.get( 'sessao_selecionada': sessao_selecionada,
id=int(request.POST['sessao'])),
'composicao_mesa': mesa, 'composicao_mesa': mesa,
'parlamentares': parlamentares_vagos, 'parlamentares': parlamentares_vagos,
'cargos_vagos': cargos_vagos 'cargos_vagos': cargos_vagos

2
sapl/templates/crud/detail.html

@ -7,7 +7,7 @@
{% block actions %} {% block actions %}
<div class="actions btn-group btn-group-sm" role="group"> <div class="actions btn-group btn-group-sm" role="group">
{% if view.list_url %} {% 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 %} {% endif %}
{% if view.create_url %} {% if view.create_url %}
<a href="{{ view.create_url }}" class="btn btn-default"> <a href="{{ view.create_url }}" class="btn btn-default">

4
sapl/templates/crud/detail_detail.html

@ -7,7 +7,7 @@
{% block actions %} {% block actions %}
<div class="actions btn-group btn-group-sm" role="group"> <div class="actions btn-group btn-group-sm" role="group">
{% if view.detail_list_url %} {% 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 %} {% endif %}
{% if view.detail_create_url %} {% if view.detail_create_url %}
<a href="{{ view.detail_create_url }}" class="btn btn-default"> <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> <a href="{{ view.update_url }}" class="btn btn-default">{% trans 'Editar' %}</a>
{% endif %} {% endif %}
{% if view.delete_url %} {% 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 %} {% endif %}
</div> </div>
{% endif %} {% endif %}

14
sapl/templates/crud/list.html

@ -34,14 +34,20 @@
<tr> <tr>
{% for name in headers %} {% for name in headers %}
<th> <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 view.ordered_list %}
{% 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 %} <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> <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> <span class="caret" title="{% trans 'Listado na Ordem Descendente'%}"></span>
{%endif%} {%endif%}
{%endif%}
</a> </a>
{% else %}
{{ name }}
{% endif %}
</th> </th>
{% endfor %} {% endfor %}
</tr> </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"> <div class="col-md-4" align="center">
<br /><br /> <br /><br />
{% if cargos_vagos %} {% 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" /> <input type="submit" name="Incluir" Value="Incluir" class="btn btn-primary" />
{% endif %} {% endif %}
{% endif %} {% endif %}
<br /> <br />
<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" /> <input type="submit" name="Excluir" Value="Excluir" class="btn btn-danger" />
{% endif %} {% endif %}
</div> </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' %} - title: {% trans 'Dependentes' %}
url: dependente_list url: dependente_list
- title: {% trans 'Comissões' %} - title: {% trans 'Comissões' %}
url: participacao_list url: participacao_parlamentar_list
- title: {% trans 'Proposições' %} - title: {% trans 'Proposições' %}
url: proposicao_list url: proposicao_parlamentar_list
- title: {% trans 'Relatorias' %} - title: {% trans 'Relatorias' %}
url: relatoria_list url: relatoria_parlamentar_list
- title: {% trans 'Frentes' %} - 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

37
scripts/inicializa_grupos_autorizacoes.py

@ -1,25 +1,34 @@
from django.apps import apps import os
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
import django
def cria_ou_reseta_grupo(nome):
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] grupo = Group.objects.get_or_create(name=nome)[0]
for p in list(grupo.permissions.all()): for p in list(grupo.permissions.all()):
grupo.permissions.remove(p) grupo.permissions.remove(p)
return grupo return grupo
def cria_usuario(nome, grupo):
def cria_usuario(nome, grupo):
nome_usuario = nome 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.set_password('interlegis')
usuario.save() usuario.save()
grupo.user_set.add(usuario) grupo.user_set.add(usuario)
def cria_grupos_permissoes():
def cria_grupos_permissoes():
nomes_apps = ['base', 'parlamentares', 'comissoes', nomes_apps = ['base', 'parlamentares', 'comissoes',
'materia', 'norma', 'sessao', 'painel'] 'materia', 'norma', 'sessao', 'painel']
@ -101,8 +110,10 @@ def cria_grupos_permissoes():
# Autor # Autor
perms_autor = [] perms_autor = []
perms_autor.append(Permission.objects.get(name='Can add Proposição')) 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(
perms_autor.append(Permission.objects.get(name='Can delete Proposição')) Permission.objects.get(name='Can change Proposição'))
perms_autor.append(
Permission.objects.get(name='Can delete Proposição'))
# Configura Permissoes Autor # Configura Permissoes Autor
grupo = cria_ou_reseta_grupo('Autor') grupo = cria_ou_reseta_grupo('Autor')
@ -112,6 +123,4 @@ def cria_grupos_permissoes():
nome_usuario = 'operador_autor' nome_usuario = 'operador_autor'
cria_usuario(nome_usuario, grupo) cria_usuario(nome_usuario, grupo)
if __name__ == '__main__':
cria_grupos_permissoes() cria_grupos_permissoes()

Loading…
Cancel
Save