Repository: interlegis/sapl

Issue:
Relatório de presença nas sessões



Discussion:

Resolving patch:
diff --git a/sapl/base/forms.py b/sapl/base/forms.py
--- a/sapl/base/forms.py
+++ b/sapl/base/forms.py
@@ -10,6 +10,7 @@
 
 from sapl.crispy_layout_mixin import form_actions, to_row
 from sapl.materia.models import MateriaLegislativa
+from sapl.sessao.models import SessaoPlenaria
 from sapl.settings import MAX_IMAGE_UPLOAD_SIZE
 from sapl.utils import (RANGE_ANOS, ImageThumbnailFileInput, autor_label,
                         autor_modal)
@@ -37,6 +38,36 @@ def format_output(self, rendered_widgets):
         return ''.join(rendered_widgets)
 
 
+class RelatorioPresencaSessaoFilterSet(django_filters.FilterSet):
+
+    filter_overrides = {models.DateField: {
+        'filter_class': django_filters.DateFromToRangeFilter,
+        'extra': lambda f: {
+            'label': '%s (%s)' % (f.verbose_name, _('Inicial - Final')),
+            'widget': RangeWidgetOverride}
+    }}
+
+    class Meta:
+        model = SessaoPlenaria
+        fields = ['data_inicio']
+
+    def __init__(self, *args, **kwargs):
+        super(RelatorioPresencaSessaoFilterSet, self).__init__(
+                *args, **kwargs)
+
+        self.filters['data_inicio'].label = 'Período (Inicial - Final)'
+        self.form.fields['data_inicio'].required = True
+
+        row1 = to_row([('data_inicio', 12)])
+
+        self.form.helper = FormHelper()
+        self.form.helper.form_method = 'GET'
+        self.form.helper.layout = Layout(
+            Fieldset(_('Presença dos parlamentares nas sessões plenárias'),
+                     row1, form_actions(save_label='Pesquisar'))
+        )
+
+
 class RelatorioHistoricoTramitacaoFilterSet(django_filters.FilterSet):
 
     filter_overrides = {models.DateField: {
diff --git a/sapl/base/urls.py b/sapl/base/urls.py
--- a/sapl/base/urls.py
+++ b/sapl/base/urls.py
@@ -8,7 +8,8 @@
                     RelatorioHistoricoTramitacaoView,
                     RelatorioMateriasPorAnoAutorTipoView,
                     RelatorioMateriasPorAutorView,
-                    RelatorioMateriasTramitacaoView)
+                    RelatorioMateriasTramitacaoView,
+                    RelatorioPresencaSessaoView)
 
 app_name = AppConfig.name
 
@@ -39,5 +40,8 @@
     url(r'^relatorio/historico-tramitacoes$',
         RelatorioHistoricoTramitacaoView.as_view(),
         name='historico_tramitacoes'),
+    url(r'^relatorio/presenca$',
+        RelatorioPresencaSessaoView.as_view(),
+        name='presenca_sessao'),
 
 ]
diff --git a/sapl/base/views.py b/sapl/base/views.py
--- a/sapl/base/views.py
+++ b/sapl/base/views.py
@@ -1,5 +1,8 @@
+from itertools import chain
+
 from django.contrib.auth.mixins import PermissionRequiredMixin
 from django.core.urlresolvers import reverse
+from django.db.models import Count, Q
 from django.http import HttpResponseRedirect
 from django.utils.translation import ugettext_lazy as _
 from django.views.generic.base import TemplateView
@@ -8,12 +11,16 @@
 from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView,
                             CrudDetailView, CrudUpdateView)
 from sapl.materia.models import MateriaLegislativa, TipoMateriaLegislativa
+from sapl.parlamentares.models import Parlamentar
+from sapl.sessao.models import (OrdemDia, PresencaOrdemDia, SessaoPlenaria,
+                                SessaoPlenariaPresenca)
 from sapl.utils import permissao_tb_aux
 
 from .forms import (CasaLegislativaForm, RelatorioHistoricoTramitacaoFilterSet,
                     RelatorioMateriasPorAnoAutorTipoFilterSet,
                     RelatorioMateriasPorAutorFilterSet,
-                    RelatorioMateriasTramitacaoilterSet)
+                    RelatorioMateriasTramitacaoilterSet,
+                    RelatorioPresencaSessaoFilterSet)
 from .models import CasaLegislativa
 
 
@@ -21,6 +28,71 @@ def get_casalegislativa():
     return CasaLegislativa.objects.first()
 
 
+class RelatorioPresencaSessaoView(FilterView):
+    model = SessaoPlenaria
+    filterset_class = RelatorioPresencaSessaoFilterSet
+    template_name = 'base/RelatorioPresencaSessao_filter.html'
+
+    def calcular_porcentagem_presenca(self,
+                                      parlamentares,
+                                      total_sessao,
+                                      total_ordemdia):
+        for p in parlamentares:
+            p.sessao_porc = round(p.sessao_count * 100 / total_sessao, 1)
+            p.ordemdia_porc = round(p.ordemdia_count * 100 / total_ordemdia, 1)
+        return parlamentares
+
+    def get_context_data(self, **kwargs):
+        context = super(RelatorioPresencaSessaoView,
+                        self).get_context_data(**kwargs)
+        context['title'] = _('Presença dos parlamentares nas sessões')
+
+        # Verifica se os campos foram preenchidos
+        if not self.filterset.form.is_valid():
+            return context
+
+        # =====================================================================
+        if 'salvar' in self.request.GET:
+            where = context['object_list'].query.where
+            _range = where.children[0].rhs
+
+            sufixo = 'sessao_plenaria__data_inicio__range'
+            param0 = {'%s' % sufixo: _range}
+            param1 = {'presencaordemdia__%s' % sufixo: _range}
+            param2 = {'sessaoplenariapresenca__%s' % sufixo: _range}
+
+            pls = Parlamentar.objects.filter(
+                Q(**param1) & Q(**param2)).annotate(
+                    sessao_count=Count(
+                       'sessaoplenariapresenca__sessao_plenaria__data_inicio',
+                       distinct=True),
+                    ordemdia_count=Count(
+                        'presencaordemdia__sessao_plenaria',
+                        distinct=True),
+                    sessao_porc=Count(0),
+                    ordemdia_porc=Count(0))
+
+            total_ordemdia = OrdemDia.objects.order_by(
+                'sessao_plenaria').filter(**param0).distinct(
+                'sessao_plenaria').count()
+
+            self.calcular_porcentagem_presenca(
+                pls,
+                context['object_list'].count(),
+                total_ordemdia)
+
+            context['total_ordemdia'] = total_ordemdia
+            context['total_sessao'] = context['object_list'].count()
+            context['parlamentares'] = pls
+            context['periodo'] = (
+                self.request.GET['data_inicio_0'] +
+                ' - ' + self.request.GET['data_inicio_1'])
+        # =====================================================================
+        qr = self.request.GET.copy()
+        context['filter_url'] = ('&' + qr.urlencode()) if len(qr) > 0 else ''
+        return context
+
+
 class RelatorioHistoricoTramitacaoView(FilterView):
     model = MateriaLegislativa
     filterset_class = RelatorioHistoricoTramitacaoFilterSet


Test patch: