From 0dfb6c306dfeb29c19b3c1a18f607ad9020089fc Mon Sep 17 00:00:00 2001 From: LeandroRoberto Date: Sun, 2 Oct 2016 22:21:43 -0300 Subject: [PATCH] Refatora app parlamentares p/ utilizar ref do Crud --- sapl/base/templatetags/menus.py | 8 +- sapl/comissoes/views.py | 2 +- sapl/crispy_layout_mixin.py | 3 + sapl/crud/base.py | 269 ++++++++---- sapl/materia/views.py | 2 +- .../0032_frenteproxymasterdetail.py | 24 + .../migrations/0033_auto_20160930_1715.py | 29 ++ .../0034_delete_frenteparlamentar.py | 18 + sapl/parlamentares/urls.py | 5 +- sapl/parlamentares/views.py | 414 ++++++------------ sapl/templates/crud/detail.html | 2 +- sapl/templates/crud/detail_detail.html | 4 +- sapl/templates/crud/list.html | 22 +- .../parlamentares/coligacao_detail.html | 10 - .../composicaomesa_form.html} | 4 +- sapl/templates/parlamentares/frentes.html | 21 - sapl/templates/parlamentares/subnav.yaml | 8 +- .../parlamentares/subnav_coligacao.yaml | 5 + scripts/inicializa_grupos_autorizacoes.py | 235 +++++----- 19 files changed, 547 insertions(+), 538 deletions(-) create mode 100644 sapl/parlamentares/migrations/0032_frenteproxymasterdetail.py create mode 100644 sapl/parlamentares/migrations/0033_auto_20160930_1715.py create mode 100644 sapl/parlamentares/migrations/0034_delete_frenteparlamentar.py delete mode 100644 sapl/templates/parlamentares/coligacao_detail.html rename sapl/templates/{mesa_diretora/mesa_diretora.html => parlamentares/composicaomesa_form.html} (93%) delete mode 100644 sapl/templates/parlamentares/frentes.html create mode 100644 sapl/templates/parlamentares/subnav_coligacao.yaml diff --git a/sapl/base/templatetags/menus.py b/sapl/base/templatetags/menus.py index 2f121d3c7..d49d4dbee 100644 --- a/sapl/base/templatetags/menus.py +++ b/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, diff --git a/sapl/comissoes/views.py b/sapl/comissoes/views.py index 1664b1209..9d7208f62 100644 --- a/sapl/comissoes/views.py +++ b/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 = [] diff --git a/sapl/crispy_layout_mixin.py b/sapl/crispy_layout_mixin.py index f691a6b55..1d0c5c17e 100644 --- a/sapl/crispy_layout_mixin.py +++ b/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] diff --git a/sapl/crud/base.py b/sapl/crud/base.py index 112577f6e..a0cc93608 100644 --- a/sapl/crud/base.py +++ b/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] - s = ' / '.join(s) - r.append(s) - else: - r.append( - self.model._meta.get_field(fieldname).verbose_name) + 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) return r def _as_row(self, obj): + """ + FIXME: Refatorar função para capturar url correta em caso de uso de + campos foreignkey. getHeaders já 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,10 +444,12 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView): del qr['page'] context['filter_url'] = ( '&' + qr.urlencode()) if len(qr) > 0 else '' - if 'o' in qr: - del qr['o'] - context['ordering_url'] = ( - '&' + qr.urlencode()) if len(qr) > 0 else '' + + if self.ordered_list: + if 'o' in qr: + del qr['o'] + context['ordering_url'] = ( + '&' + qr.urlencode()) if len(qr) > 0 else '' return context def get_queryset(self): @@ -447,53 +473,61 @@ class CrudListView(PermissionRequiredContainerCrudMixin, ListView): if q: queryset = queryset.filter(q) - list_field_names = self.list_field_names - o = '1' - desc = '' - if 'o' in self.request.GET: - o = self.request.GET['o'] - desc = '-' if o.startswith('-') else '' + if self.ordered_list: + list_field_names = self.list_field_names + o = '1' + desc = '' + if 'o' in self.request.GET: + o = self.request.GET['o'] + desc = '-' if o.startswith('-') else '' - # 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)] - - if isinstance(fields_for_ordering, str): - fields_for_ordering = [fields_for_ordering, ] - - ordering = () - model = self.model - for fo in fields_for_ordering: - fm = model._meta.get_field(fo) - if hasattr(fm, 'related_model') and fm.related_model: - rmo = fm.related_model._meta.ordering - if rmo: - rmo = rmo[0] - if not isinstance(rmo, str): + # 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)] + + if isinstance(fields_for_ordering, str): + fields_for_ordering = [fields_for_ordering, ] + + ordering = () + model = self.model + for fo in fields_for_ordering: + + fm = None + try: + fm = model._meta.get_field(fo) + except: + pass + + if fm and hasattr(fm, 'related_model')\ + and fm.related_model: + rmo = fm.related_model._meta.ordering + if rmo: rmo = rmo[0] - fo = '%s__%s' % (fo, rmo) - - fo = desc + fo - ordering += (fo,) - - model = self.model - model_ordering = model._meta.ordering - if model_ordering: - if isinstance(model_ordering, str): - model_ordering = (model_ordering,) - for mo in model_ordering: - if mo not in ordering: - ordering = ordering + (mo, ) - queryset = queryset.order_by(*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)) - + if not isinstance(rmo, str): + rmo = rmo[0] + fo = '%s__%s' % (fo, rmo) + + fo = desc + fo + ordering += (fo,) + + model = self.model + model_ordering = model._meta.ordering + if model_ordering: + if isinstance(model_ordering, str): + model_ordering = (model_ordering,) + for mo in model_ordering: + if mo not in ordering: + ordering = ordering + (mo, ) + queryset = queryset.order_by(*ordering) + + # print(ordering) + except Exception as e: + logger.error(string_concat(_( + '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,16 +798,20 @@ class Crud: DeleteView = CrudDeleteView help_path = '' + class PublicMixin: + permission_required = [] + @classonlymethod def get_urls(cls): def _add_base(view): - class CrudViewWithBase(cls.BaseMixin, view): - model = cls.model - help_path = cls.help_path - crud = cls - CrudViewWithBase.__name__ = view.__name__ - return CrudViewWithBase + if view: + class CrudViewWithBase(cls.BaseMixin, view): + model = cls.model + help_path = cls.help_path + crud = cls + CrudViewWithBase.__name__ = view.__name__ + return CrudViewWithBase CrudListView = _add_base(cls.ListView) CrudCreateView = _add_base(cls.CreateView) @@ -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) diff --git a/sapl/materia/views.py b/sapl/materia/views.py index cee9abd19..c80bcc38f 100644 --- a/sapl/materia/views.py +++ b/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 diff --git a/sapl/parlamentares/migrations/0032_frenteproxymasterdetail.py b/sapl/parlamentares/migrations/0032_frenteproxymasterdetail.py new file mode 100644 index 000000000..8974be563 --- /dev/null +++ b/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',), + ), + ] diff --git a/sapl/parlamentares/migrations/0033_auto_20160930_1715.py b/sapl/parlamentares/migrations/0033_auto_20160930_1715.py new file mode 100644 index 000000000..14591d16c --- /dev/null +++ b/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',), + ), + ] diff --git a/sapl/parlamentares/migrations/0034_delete_frenteparlamentar.py b/sapl/parlamentares/migrations/0034_delete_frenteparlamentar.py new file mode 100644 index 000000000..4c5e8d710 --- /dev/null +++ b/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', + ), + ] diff --git a/sapl/parlamentares/urls.py b/sapl/parlamentares/urls.py index 70af2200a..a977992f8 100644 --- a/sapl/parlamentares/urls.py +++ b/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\d+)/frente$', - FrenteList.as_view(), name="frent_list"), - url(r'^sistema/coligacao/', include(ColigacaoCrud.get_urls() + ComposicaoColigacaoCrud.get_urls())), diff --git a/sapl/parlamentares/views.py b/sapl/parlamentares/views.py index c751dba87..4bdc115dc 100644 --- a/sapl/parlamentares/views.py +++ b/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 + list_field_names = ['tipo', 'descricao'] parent_field = 'autor__parlamentar' - help_path = '' - - class BaseMixin(CrudBaseMixin): - list_field_names = ['tipo', 'descricao'] - - class ListView(MasterDetailCrud.ListView): - permission_required = permissoes_parlamentares() + namespace = AppConfig.name - 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( - autor__parlamentar_id=self.kwargs['pk'], - data_envio__isnull=False) - except ObjectDoesNotExist: - return [] - else: - return proposicoes + return super().get_queryset().filter( + autor__parlamentar_id=self.kwargs['pk'], + data_envio__isnull=False) - 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' + return [_('Comissão'), _('Cargo'), _('Período de participação'), ] - 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): - - 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,22 +286,25 @@ 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()): - return self.validation(request) + 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( @@ -472,13 +315,12 @@ class MesaDiretoraView(FormView): id=int(request.POST['cargo'])) 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 - 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,32 +330,42 @@ class MesaDiretoraView(FormView): cargo_id=int(ids[1]) ) composicao.delete() - return redirect('sapl.parlamentares:mesa_diretora') - else: - mesa = ComposicaoMesa.objects.filter( - sessao_legislativa=request.POST['sessao']) - - cargos_ocupados = [m.cargo for m in mesa] - cargos = CargoMesa.objects.all() - cargos_vagos = list(set(cargos) - set(cargos_ocupados)) - - parlamentares = Legislatura.objects.get( - id=int(request.POST['legislatura'])).mandato_set.all() - parlamentares_ocupados = [m.parlamentar for m in mesa] - parlamentares_vagos = list( - set( - [p.parlamentar for p in parlamentares]) - set( - parlamentares_ocupados)) - return self.render_to_response( - {'legislaturas': Legislatura.objects.all( - ).order_by('-numero'), - 'legislatura_selecionada': Legislatura.objects.get( - 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'])), - 'composicao_mesa': mesa, - 'parlamentares': parlamentares_vagos, - 'cargos_vagos': cargos_vagos - }) + 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']) + + cargos_ocupados = [m.cargo for m in mesa] + cargos = CargoMesa.objects.all() + cargos_vagos = list(set(cargos) - set(cargos_ocupados)) + + parlamentares = Legislatura.objects.get( + id=int(request.POST['legislatura'])).mandato_set.all() + parlamentares_ocupados = [m.parlamentar for m in mesa] + parlamentares_vagos = list( + 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'), + 'legislatura_selecionada': Legislatura.objects.get( + id=int(request.POST['legislatura'])), + 'sessoes': SessaoLegislativa.objects.filter( + legislatura_id=int(request.POST['legislatura'])), + 'sessao_selecionada': sessao_selecionada, + 'composicao_mesa': mesa, + 'parlamentares': parlamentares_vagos, + 'cargos_vagos': cargos_vagos + }) diff --git a/sapl/templates/crud/detail.html b/sapl/templates/crud/detail.html index b491e20ce..0992bc345 100644 --- a/sapl/templates/crud/detail.html +++ b/sapl/templates/crud/detail.html @@ -7,7 +7,7 @@ {% block actions %}
{% if view.list_url %} - {% trans 'Listar' %} {{view.verbose_name_plural}} + {% trans 'Listar' %} {{view.verbose_name_plural}} {% endif %} {% if view.create_url %} diff --git a/sapl/templates/crud/detail_detail.html b/sapl/templates/crud/detail_detail.html index d3bd5e653..006ec1b57 100644 --- a/sapl/templates/crud/detail_detail.html +++ b/sapl/templates/crud/detail_detail.html @@ -7,7 +7,7 @@ {% block actions %} {% endif %} diff --git a/sapl/templates/crud/list.html b/sapl/templates/crud/list.html index 9169ade96..d89caab5d 100644 --- a/sapl/templates/crud/list.html +++ b/sapl/templates/crud/list.html @@ -34,14 +34,20 @@ {% for name in headers %} - {{ 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 %} - - {% 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 %} - - {%endif%} - - + {% if view.ordered_list %} + + {{ 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 %} + + {% elif 'o' in request.GET and forloop.counter == request.GET.o|str2intabs %} + + {%endif%} + {%endif%} + + {% else %} + {{ name }} + {% endif %} {% endfor %} diff --git a/sapl/templates/parlamentares/coligacao_detail.html b/sapl/templates/parlamentares/coligacao_detail.html deleted file mode 100644 index 02345a4e9..000000000 --- a/sapl/templates/parlamentares/coligacao_detail.html +++ /dev/null @@ -1,10 +0,0 @@ -{% extends "crud/detail.html" %} -{% load i18n %} - -{% block actions %} - -{% endblock actions %} \ No newline at end of file diff --git a/sapl/templates/mesa_diretora/mesa_diretora.html b/sapl/templates/parlamentares/composicaomesa_form.html similarity index 93% rename from sapl/templates/mesa_diretora/mesa_diretora.html rename to sapl/templates/parlamentares/composicaomesa_form.html index 0443201e7..d8f08ac30 100644 --- a/sapl/templates/mesa_diretora/mesa_diretora.html +++ b/sapl/templates/parlamentares/composicaomesa_form.html @@ -48,13 +48,13 @@


{% if cargos_vagos %} - {% if perms.parlamentares.add_cargomesa or perms.parlamentares.add_composicaomesa %} + {% if perms.parlamentares.add_cargomesa%} {% endif %} {% endif %}

- {% if perms.parlamentares.add_cargomesa or perms.parlamentares.add_composicaomesa %} + {% if perms.parlamentares.add_composicaomesa %} {% endif %}
diff --git a/sapl/templates/parlamentares/frentes.html b/sapl/templates/parlamentares/frentes.html deleted file mode 100644 index 5a7ae3f9e..000000000 --- a/sapl/templates/parlamentares/frentes.html +++ /dev/null @@ -1,21 +0,0 @@ -{% extends "crud/list.html" %} -{% load i18n %} -{% load crispy_forms_tags %} - -{% block base_content %} - {% if object_list|length == 0 %} -

Nenhuma frente encontrada.

- {% else %} - - - - - - {% for frente in object_list %} - - {% endfor %} - -
Frentes
{{ frente.nome }}
- {% endif %} - {% include "paginacao.html" %} -{% endblock %} diff --git a/sapl/templates/parlamentares/subnav.yaml b/sapl/templates/parlamentares/subnav.yaml index 6463640d8..8d9c4e65b 100644 --- a/sapl/templates/parlamentares/subnav.yaml +++ b/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 diff --git a/sapl/templates/parlamentares/subnav_coligacao.yaml b/sapl/templates/parlamentares/subnav_coligacao.yaml new file mode 100644 index 000000000..513d92ef8 --- /dev/null +++ b/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 diff --git a/scripts/inicializa_grupos_autorizacoes.py b/scripts/inicializa_grupos_autorizacoes.py index 1377d66e6..8e14768b2 100644 --- a/scripts/inicializa_grupos_autorizacoes.py +++ b/scripts/inicializa_grupos_autorizacoes.py @@ -1,117 +1,126 @@ -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.set_password('interlegis') - usuario.save() - grupo.user_set.add(usuario) - - -def cria_grupos_permissoes(): - - nomes_apps = ['base', 'parlamentares', 'comissoes', - 'materia', 'norma', 'sessao', 'painel'] - - permissoes = {app: list(Permission.objects.filter( - content_type__in=ContentType.objects.filter(app_label=app))) - for app in nomes_apps} - - # permissoes específicas para protocolo e documento administrativo - cts = ContentType.objects.filter(app_label='protocoloadm') - - # documento administrativo - permissoes['documento_administrativo'] = list( - Permission.objects.filter(content_type__in=cts)) - nome_grupo = 'Operador Administrativo' - grupo = cria_ou_reseta_grupo(nome_grupo) - for p in permissoes['documento_administrativo']: - grupo.permissions.add(p) - - nome_usuario = 'operador_administrativo' - cria_usuario(nome_usuario, grupo) - - # prolocolo administrativo - cts = cts.exclude(model__icontains='tramitacao').exclude( - model__icontains='documentoadministrativo') - permissoes['protocoloadm'] = list( - Permission.objects.filter(content_type__in=cts)) - nome_grupo = 'Operador de Protocolo Administrativo' - grupo = cria_ou_reseta_grupo(nome_grupo) - for p in permissoes['protocoloadm']: - grupo.permissions.add(p) - - nome_usuario = 'operador_protocoloadm' - cria_usuario(nome_usuario, grupo) - - # permissoes do base - cts = ContentType.objects.filter(app_label='base') - permissoes['base'] = list( - Permission.objects.filter(content_type__in=cts)) - - for nome_app in nomes_apps: - - if nome_app not in {'base', 'parlamentares'}: - # Elimina casos especificos - - # Cria Grupo - nome_grupo = 'Operador de %s' % apps.get_app_config( - nome_app).verbose_name - grupo = cria_ou_reseta_grupo(nome_grupo) - - # Elimina o acesso a proposicoes pelo Operador de Matérias - if nome_app == 'materia': - cts = ContentType.objects.filter( - app_label='materia').exclude(model='proposicao') - permissoes['materia'] = list( - Permission.objects.filter(content_type__in=cts)) - - # Configura as permissoes - for p in permissoes[nome_app]: - grupo.permissions.add(p) - - # Cria o Usuario - nome_usuario = 'operador_%s' % nome_app - usuario = get_user_model().objects.get_or_create( - username=nome_usuario)[0] - usuario.set_password('interlegis') - usuario.save() - grupo.user_set.add(usuario) - - # Operador Geral - grupo_geral = cria_ou_reseta_grupo('Operador Geral') - for lista in permissoes.values(): - for p in lista: - grupo_geral.permissions.add(p) - - nome_usuario = 'operador_geral' - cria_usuario(nome_usuario, grupo_geral) - - # 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')) - - # Configura Permissoes Autor - grupo = cria_ou_reseta_grupo('Autor') - for p in perms_autor: - grupo.permissions.add(p) - - nome_usuario = 'operador_autor' - cria_usuario(nome_usuario, grupo) +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.set_password('interlegis') + usuario.save() + grupo.user_set.add(usuario) + + def cria_grupos_permissoes(): + + nomes_apps = ['base', 'parlamentares', 'comissoes', + 'materia', 'norma', 'sessao', 'painel'] + + permissoes = {app: list(Permission.objects.filter( + content_type__in=ContentType.objects.filter(app_label=app))) + for app in nomes_apps} + + # permissoes específicas para protocolo e documento administrativo + cts = ContentType.objects.filter(app_label='protocoloadm') + + # documento administrativo + permissoes['documento_administrativo'] = list( + Permission.objects.filter(content_type__in=cts)) + nome_grupo = 'Operador Administrativo' + grupo = cria_ou_reseta_grupo(nome_grupo) + for p in permissoes['documento_administrativo']: + grupo.permissions.add(p) + + nome_usuario = 'operador_administrativo' + cria_usuario(nome_usuario, grupo) + + # prolocolo administrativo + cts = cts.exclude(model__icontains='tramitacao').exclude( + model__icontains='documentoadministrativo') + permissoes['protocoloadm'] = list( + Permission.objects.filter(content_type__in=cts)) + nome_grupo = 'Operador de Protocolo Administrativo' + grupo = cria_ou_reseta_grupo(nome_grupo) + for p in permissoes['protocoloadm']: + grupo.permissions.add(p) + + nome_usuario = 'operador_protocoloadm' + cria_usuario(nome_usuario, grupo) + + # permissoes do base + cts = ContentType.objects.filter(app_label='base') + permissoes['base'] = list( + Permission.objects.filter(content_type__in=cts)) + + for nome_app in nomes_apps: + + if nome_app not in {'base', 'parlamentares'}: + # Elimina casos especificos + + # Cria Grupo + nome_grupo = 'Operador de %s' % apps.get_app_config( + nome_app).verbose_name + grupo = cria_ou_reseta_grupo(nome_grupo) + + # Elimina o acesso a proposicoes pelo Operador de Matérias + if nome_app == 'materia': + cts = ContentType.objects.filter( + app_label='materia').exclude(model='proposicao') + permissoes['materia'] = list( + Permission.objects.filter(content_type__in=cts)) + + # Configura as permissoes + for p in permissoes[nome_app]: + grupo.permissions.add(p) + + # Cria o Usuario + nome_usuario = 'operador_%s' % nome_app + usuario = get_user_model().objects.get_or_create( + username=nome_usuario)[0] + usuario.set_password('interlegis') + usuario.save() + grupo.user_set.add(usuario) + + # Operador Geral + grupo_geral = cria_ou_reseta_grupo('Operador Geral') + for lista in permissoes.values(): + for p in lista: + grupo_geral.permissions.add(p) + + nome_usuario = 'operador_geral' + cria_usuario(nome_usuario, grupo_geral) + + # 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')) + + # Configura Permissoes Autor + grupo = cria_ou_reseta_grupo('Autor') + for p in perms_autor: + grupo.permissions.add(p) + + nome_usuario = 'operador_autor' + cria_usuario(nome_usuario, grupo) + cria_grupos_permissoes()