We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Total de registros encontrados em relatório está por página e não por total
Em Comissões, Matérias em Tramitação, a contagem está relacionada ao número de matérias por página e não pelo total na unidade.

Ex:

https://sapl.divinopolis.mg.leg.br/comissao/101/materias-em-tramitacao

## Comportamento Esperado
A tela deve trazer a quantidade total de registros recuperados, não o total por página.

## Comportamento Atual
A página traz a quantidade de registros por página.

## Passos para Reproduzir (para bugs)
1. Acesse o link https://sapl.divinopolis.mg.leg.br/comissao/101/materias-em-tramitacao

## Seu Ambiente
<!--- Inclua detalhes relevantes sobre o ambiente em que você presenciou/experienciou o bug. -->
* Versão usada (_Release_): 3.1.147
* Nome e versão do navegador: Chrome
* Nome e versão do Sistema Operacional (desktop ou mobile): Linux
* Link para o seu projeto (Caso de fork deste projeto):


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `sapl/comissoes/views.py`
Content:
```
1 import logging
2 
3 from django.core.urlresolvers import reverse
4 from django.db.models import F
5 from django.http.response import HttpResponseRedirect
6 from django.views.decorators.clickjacking import xframe_options_exempt
7 from django.views.generic import ListView
8 from django.views.generic.base import RedirectView
9 from django.views.generic.detail import DetailView
10 from django.views.generic.edit import FormMixin
11 
12 from sapl.base.models import AppConfig as AppsAppConfig
13 from sapl.comissoes.apps import AppConfig
14 from sapl.comissoes.forms import (ComissaoForm, ComposicaoForm,
15                                   DocumentoAcessorioCreateForm,
16                                   DocumentoAcessorioEditForm,
17                                   ParticipacaoCreateForm, ParticipacaoEditForm,
18                                   PeriodoForm, ReuniaoForm)
19 from sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,
20                             MasterDetailCrud,
21                             PermissionRequiredForAppCrudMixin)
22 from sapl.materia.models import MateriaLegislativa, Tramitacao
23 
24 from .models import (CargoComissao, Comissao, Composicao, DocumentoAcessorio,
25                      Participacao, Periodo, Reuniao, TipoComissao)
26 
27 
28 def pegar_url_composicao(pk):
29     participacao = Participacao.objects.get(id=pk)
30     comp_pk = participacao.composicao.pk
31     url = reverse('sapl.comissoes:composicao_detail', kwargs={'pk': comp_pk})
32     return url
33 
34 
35 def pegar_url_reuniao(pk):
36     documentoacessorio = DocumentoAcessorio.objects.get(id=pk)
37     r_pk = documentoacessorio.reuniao.pk
38     url = reverse('sapl.comissoes:reuniao_detail', kwargs={'pk': r_pk})
39     return url
40 
41 CargoCrud = CrudAux.build(CargoComissao, 'cargo_comissao')
42 
43 TipoComissaoCrud = CrudAux.build(
44     TipoComissao, 'tipo_comissao', list_field_names=[
45         'sigla', 'nome', 'natureza', 'dispositivo_regimental'])
46 
47 
48 class PeriodoComposicaoCrud(CrudAux):
49     model = Periodo
50 
51     class CreateView(CrudAux.CreateView):
52         form_class = PeriodoForm
53 
54     class UpdateView(CrudAux.UpdateView):
55         form_class = PeriodoForm
56 
57     # class ListView(CrudAux.ListView):
58 
59 
60 class ParticipacaoCrud(MasterDetailCrud):
61     model = Participacao
62     parent_field = 'composicao__comissao'
63     public = [RP_DETAIL, ]
64     ListView = None
65     link_return_to_parent_field = True
66 
67     class BaseMixin(MasterDetailCrud.BaseMixin):
68         list_field_names = ['composicao', 'parlamentar', 'cargo']
69 
70     class CreateView(MasterDetailCrud.CreateView):
71         form_class = ParticipacaoCreateForm
72 
73         def get_initial(self):
74             initial = super().get_initial()
75             initial['parent_pk'] = self.kwargs['pk']
76             return initial
77 
78     class UpdateView(MasterDetailCrud.UpdateView):
79         layout_key = 'ParticipacaoEdit'
80         form_class = ParticipacaoEditForm
81 
82     class DeleteView(MasterDetailCrud.DeleteView):
83 
84         def get_success_url(self):
85             composicao_comissao_pk = self.object.composicao.comissao.pk
86             composicao_pk = self.object.composicao.pk
87             return '{}?pk={}'.format(reverse('sapl.comissoes:composicao_list',
88                                              args=[composicao_comissao_pk]),
89                                      composicao_pk)
90 
91 
92 class ComposicaoCrud(MasterDetailCrud):
93     model = Composicao
94     parent_field = 'comissao'
95     model_set = 'participacao_set'
96     public = [RP_LIST, RP_DETAIL, ]
97 
98     class CreateView(MasterDetailCrud.CreateView):
99         form_class = ComposicaoForm
100 
101         def get_initial(self):
102             comissao = Comissao.objects.get(id=self.kwargs['pk'])
103             return {'comissao': comissao}
104 
105     class ListView(MasterDetailCrud.ListView):
106         logger = logging.getLogger(__name__)
107         template_name = "comissoes/composicao_list.html"
108         paginate_by = None
109 
110         def take_composicao_pk(self):
111             
112             username = self.request.user.username
113             try:
114                 self.logger.debug('user=' + username + '. Tentando obter pk da composição.')
115                 return int(self.request.GET['pk'])
116             except Exception as e:
117                 self.logger.error('user=' + username + '. Erro ao obter pk da composição. Retornado 0. ' + str(e))
118                 return 0
119 
120         def get_context_data(self, **kwargs):
121             context = super().get_context_data(**kwargs)
122 
123             composicao_pk = self.take_composicao_pk()
124 
125             if composicao_pk == 0:
126                 # Composicao eh ordenada por Periodo, que por sua vez esta em
127                 # ordem descrescente de data de inicio (issue #1920)
128                 ultima_composicao = context['composicao_list'].first()
129                 if ultima_composicao:
130                     context['composicao_pk'] = ultima_composicao.pk
131                 else:
132                     context['composicao_pk'] = 0
133             else:
134                 context['composicao_pk'] = composicao_pk
135 
136             context['participacao_set'] = Participacao.objects.filter(
137                 composicao__pk=context['composicao_pk']
138             ).order_by('id')
139             return context
140 
141 
142 class ComissaoCrud(Crud):
143     model = Comissao
144     help_topic = 'modulo_comissoes'
145     public = [RP_LIST, RP_DETAIL, ]
146 
147     class BaseMixin(Crud.BaseMixin):
148         list_field_names = ['nome', 'sigla', 'tipo',
149                             'data_criacao', 'data_extincao', 'ativa']
150         ordering = '-ativa', 'sigla'
151 
152     class CreateView(Crud.CreateView):
153         form_class = ComissaoForm
154 
155         def form_valid(self, form):
156             return super(Crud.CreateView, self).form_valid(form)
157 
158     class UpdateView(Crud.UpdateView):
159         form_class = ComissaoForm
160 
161         def form_valid(self, form):
162             return super(Crud.UpdateView, self).form_valid(form)
163 
164 
165 class MateriasTramitacaoListView(ListView):
166     template_name = "comissoes/materias_em_tramitacao.html"
167     paginate_by = 10
168 
169     def get_queryset(self):
170         # FIXME: Otimizar consulta
171         ts = Tramitacao.objects.order_by(
172             'materia', '-data_tramitacao', '-id').annotate(
173             comissao=F('unidade_tramitacao_destino__comissao')).distinct(
174                 'materia').values_list('materia', 'comissao')
175 
176         ts = list(filter(lambda x: x[1] == int(self.kwargs['pk']), ts))
177         ts = list(zip(*ts))
178         ts = ts[0] if ts else []
179 
180         materias = MateriaLegislativa.objects.filter(
181             pk__in=ts).order_by('tipo', '-ano', '-numero')
182 
183         return materias
184 
185     def get_context_data(self, **kwargs):
186         context = super(
187             MateriasTramitacaoListView, self).get_context_data(**kwargs)
188         context['object'] = Comissao.objects.get(id=self.kwargs['pk'])
189         return context
190 
191 
192 class ReuniaoCrud(MasterDetailCrud):
193     model = Reuniao
194     parent_field = 'comissao'
195     model_set = 'documentoacessorio_set'
196     public = [RP_LIST, RP_DETAIL, ]
197 
198     class BaseMixin(MasterDetailCrud.BaseMixin):
199         list_field_names = ['data', 'nome', 'tema']
200 
201     class ListView(MasterDetailCrud.ListView):
202         logger = logging.getLogger(__name__)
203         paginate_by = 10
204 
205         def take_reuniao_pk(self):
206 
207             username = self.request.user.username
208             try:
209                 self.logger.debug('user=' + username + '. Tentando obter pk da reunião.')
210                 return int(self.request.GET['pk'])
211             except Exception as e:
212                 self.logger.error('user=' + username + '. Erro ao obter pk da reunião. Retornado 0. ' + str(e))
213                 return 0
214 
215         def get_context_data(self, **kwargs):
216             context = super().get_context_data(**kwargs)
217 
218             reuniao_pk = self.take_reuniao_pk()
219 
220             if reuniao_pk == 0:
221                 ultima_reuniao = list(context['reuniao_list'])
222                 if len(ultima_reuniao) > 0:
223                     ultimo = ultima_reuniao[-1]
224                     context['reuniao_pk'] = ultimo.pk
225                 else:
226                     context['reuniao_pk'] = 0
227             else:
228                 context['reuniao_pk'] = reuniao_pk
229 
230             context['documentoacessorio_set'] = DocumentoAcessorio.objects.filter(
231                 reuniao__pk=context['reuniao_pk']
232             ).order_by('id')
233             return context
234 
235     class UpdateView(MasterDetailCrud.UpdateView):
236         form_class = ReuniaoForm
237 
238         def get_initial(self):
239             return {'comissao': self.object.comissao}
240 
241     class CreateView(MasterDetailCrud.CreateView):
242         form_class = ReuniaoForm
243 
244         def get_initial(self):
245             comissao = Comissao.objects.get(id=self.kwargs['pk'])
246 
247             return {'comissao': comissao}
248 
249 
250 class DocumentoAcessorioCrud(MasterDetailCrud):
251     model = DocumentoAcessorio
252     parent_field = 'reuniao__comissao'
253     public = [RP_DETAIL, ]
254     ListView = None
255     link_return_to_parent_field = True
256 
257     class BaseMixin(MasterDetailCrud.BaseMixin):
258         list_field_names = ['nome', 'tipo', 'data', 'autor', 'arquivo']
259 
260     class CreateView(MasterDetailCrud.CreateView):
261         form_class = DocumentoAcessorioCreateForm
262 
263         def get_initial(self):
264             initial = super().get_initial()
265             initial['parent_pk'] = self.kwargs['pk']
266             return initial
267 
268     class UpdateView(MasterDetailCrud.UpdateView):
269         layout_key = 'DocumentoAcessorioEdit'
270         form_class = DocumentoAcessorioEditForm
271 
272     class DeleteView(MasterDetailCrud.DeleteView):
273 
274         def delete(self, *args, **kwargs):
275             obj = self.get_object()
276             obj.delete()
277             return HttpResponseRedirect(
278                 reverse('sapl.comissoes:reuniao_detail',
279                         kwargs={'pk': obj.reuniao.pk}))
280
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/sapl/comissoes/views.py b/sapl/comissoes/views.py
--- a/sapl/comissoes/views.py
+++ b/sapl/comissoes/views.py
@@ -186,6 +186,7 @@
         context = super(
             MateriasTramitacaoListView, self).get_context_data(**kwargs)
         context['object'] = Comissao.objects.get(id=self.kwargs['pk'])
+        context['qtde'] = self.object_list.count()
         return context

{"golden_diff": "diff --git a/sapl/comissoes/views.py b/sapl/comissoes/views.py\n--- a/sapl/comissoes/views.py\n+++ b/sapl/comissoes/views.py\n@@ -186,6 +186,7 @@\n         context = super(\n             MateriasTramitacaoListView, self).get_context_data(**kwargs)\n         context['object'] = Comissao.objects.get(id=self.kwargs['pk'])\n+        context['qtde'] = self.object_list.count()\n         return context\n", "issue": "Total de registros encontrados em relat\u00f3rio est\u00e1 por p\u00e1gina e n\u00e3o por total\nEm Comiss\u00f5es, Mat\u00e9rias em Tramita\u00e7\u00e3o, a contagem est\u00e1 relacionada ao n\u00famero de mat\u00e9rias por p\u00e1gina e n\u00e3o pelo total na unidade.\r\n\r\nEx:\r\n\r\nhttps://sapl.divinopolis.mg.leg.br/comissao/101/materias-em-tramitacao\r\n\r\n## Comportamento Esperado\r\nA tela deve trazer a quantidade total de registros recuperados, n\u00e3o o total por p\u00e1gina.\r\n\r\n## Comportamento Atual\r\nA p\u00e1gina traz a quantidade de registros por p\u00e1gina.\r\n\r\n## Passos para Reproduzir (para bugs)\r\n1. Acesse o link https://sapl.divinopolis.mg.leg.br/comissao/101/materias-em-tramitacao\r\n\r\n## Seu Ambiente\r\n<!--- Inclua detalhes relevantes sobre o ambiente em que voc\u00ea presenciou/experienciou o bug. -->\r\n* Vers\u00e3o usada (_Release_): 3.1.147\r\n* Nome e vers\u00e3o do navegador: Chrome\r\n* Nome e vers\u00e3o do Sistema Operacional (desktop ou mobile): Linux\r\n* Link para o seu projeto (Caso de fork deste projeto):\r\n\n", "before_files": [{"content": "import logging\n\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import F\nfrom django.http.response import HttpResponseRedirect\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nfrom django.views.generic import ListView\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import FormMixin\n\nfrom sapl.base.models import AppConfig as AppsAppConfig\nfrom sapl.comissoes.apps import AppConfig\nfrom sapl.comissoes.forms import (ComissaoForm, ComposicaoForm,\n                                  DocumentoAcessorioCreateForm,\n                                  DocumentoAcessorioEditForm,\n                                  ParticipacaoCreateForm, ParticipacaoEditForm,\n                                  PeriodoForm, ReuniaoForm)\nfrom sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,\n                            MasterDetailCrud,\n                            PermissionRequiredForAppCrudMixin)\nfrom sapl.materia.models import MateriaLegislativa, Tramitacao\n\nfrom .models import (CargoComissao, Comissao, Composicao, DocumentoAcessorio,\n                     Participacao, Periodo, Reuniao, TipoComissao)\n\n\ndef pegar_url_composicao(pk):\n    participacao = Participacao.objects.get(id=pk)\n    comp_pk = participacao.composicao.pk\n    url = reverse('sapl.comissoes:composicao_detail', kwargs={'pk': comp_pk})\n    return url\n\n\ndef pegar_url_reuniao(pk):\n    documentoacessorio = DocumentoAcessorio.objects.get(id=pk)\n    r_pk = documentoacessorio.reuniao.pk\n    url = reverse('sapl.comissoes:reuniao_detail', kwargs={'pk': r_pk})\n    return url\n\nCargoCrud = CrudAux.build(CargoComissao, 'cargo_comissao')\n\nTipoComissaoCrud = CrudAux.build(\n    TipoComissao, 'tipo_comissao', list_field_names=[\n        'sigla', 'nome', 'natureza', 'dispositivo_regimental'])\n\n\nclass PeriodoComposicaoCrud(CrudAux):\n    model = Periodo\n\n    class CreateView(CrudAux.CreateView):\n        form_class = PeriodoForm\n\n    class UpdateView(CrudAux.UpdateView):\n        form_class = PeriodoForm\n\n    # class ListView(CrudAux.ListView):\n\n\nclass ParticipacaoCrud(MasterDetailCrud):\n    model = Participacao\n    parent_field = 'composicao__comissao'\n    public = [RP_DETAIL, ]\n    ListView = None\n    link_return_to_parent_field = True\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['composicao', 'parlamentar', 'cargo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = ParticipacaoCreateForm\n\n        def get_initial(self):\n            initial = super().get_initial()\n            initial['parent_pk'] = self.kwargs['pk']\n            return initial\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        layout_key = 'ParticipacaoEdit'\n        form_class = ParticipacaoEditForm\n\n    class DeleteView(MasterDetailCrud.DeleteView):\n\n        def get_success_url(self):\n            composicao_comissao_pk = self.object.composicao.comissao.pk\n            composicao_pk = self.object.composicao.pk\n            return '{}?pk={}'.format(reverse('sapl.comissoes:composicao_list',\n                                             args=[composicao_comissao_pk]),\n                                     composicao_pk)\n\n\nclass ComposicaoCrud(MasterDetailCrud):\n    model = Composicao\n    parent_field = 'comissao'\n    model_set = 'participacao_set'\n    public = [RP_LIST, RP_DETAIL, ]\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = ComposicaoForm\n\n        def get_initial(self):\n            comissao = Comissao.objects.get(id=self.kwargs['pk'])\n            return {'comissao': comissao}\n\n    class ListView(MasterDetailCrud.ListView):\n        logger = logging.getLogger(__name__)\n        template_name = \"comissoes/composicao_list.html\"\n        paginate_by = None\n\n        def take_composicao_pk(self):\n            \n            username = self.request.user.username\n            try:\n                self.logger.debug('user=' + username + '. Tentando obter pk da composi\u00e7\u00e3o.')\n                return int(self.request.GET['pk'])\n            except Exception as e:\n                self.logger.error('user=' + username + '. Erro ao obter pk da composi\u00e7\u00e3o. Retornado 0. ' + str(e))\n                return 0\n\n        def get_context_data(self, **kwargs):\n            context = super().get_context_data(**kwargs)\n\n            composicao_pk = self.take_composicao_pk()\n\n            if composicao_pk == 0:\n                # Composicao eh ordenada por Periodo, que por sua vez esta em\n                # ordem descrescente de data de inicio (issue #1920)\n                ultima_composicao = context['composicao_list'].first()\n                if ultima_composicao:\n                    context['composicao_pk'] = ultima_composicao.pk\n                else:\n                    context['composicao_pk'] = 0\n            else:\n                context['composicao_pk'] = composicao_pk\n\n            context['participacao_set'] = Participacao.objects.filter(\n                composicao__pk=context['composicao_pk']\n            ).order_by('id')\n            return context\n\n\nclass ComissaoCrud(Crud):\n    model = Comissao\n    help_topic = 'modulo_comissoes'\n    public = [RP_LIST, RP_DETAIL, ]\n\n    class BaseMixin(Crud.BaseMixin):\n        list_field_names = ['nome', 'sigla', 'tipo',\n                            'data_criacao', 'data_extincao', 'ativa']\n        ordering = '-ativa', 'sigla'\n\n    class CreateView(Crud.CreateView):\n        form_class = ComissaoForm\n\n        def form_valid(self, form):\n            return super(Crud.CreateView, self).form_valid(form)\n\n    class UpdateView(Crud.UpdateView):\n        form_class = ComissaoForm\n\n        def form_valid(self, form):\n            return super(Crud.UpdateView, self).form_valid(form)\n\n\nclass MateriasTramitacaoListView(ListView):\n    template_name = \"comissoes/materias_em_tramitacao.html\"\n    paginate_by = 10\n\n    def get_queryset(self):\n        # FIXME: Otimizar consulta\n        ts = Tramitacao.objects.order_by(\n            'materia', '-data_tramitacao', '-id').annotate(\n            comissao=F('unidade_tramitacao_destino__comissao')).distinct(\n                'materia').values_list('materia', 'comissao')\n\n        ts = list(filter(lambda x: x[1] == int(self.kwargs['pk']), ts))\n        ts = list(zip(*ts))\n        ts = ts[0] if ts else []\n\n        materias = MateriaLegislativa.objects.filter(\n            pk__in=ts).order_by('tipo', '-ano', '-numero')\n\n        return materias\n\n    def get_context_data(self, **kwargs):\n        context = super(\n            MateriasTramitacaoListView, self).get_context_data(**kwargs)\n        context['object'] = Comissao.objects.get(id=self.kwargs['pk'])\n        return context\n\n\nclass ReuniaoCrud(MasterDetailCrud):\n    model = Reuniao\n    parent_field = 'comissao'\n    model_set = 'documentoacessorio_set'\n    public = [RP_LIST, RP_DETAIL, ]\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['data', 'nome', 'tema']\n\n    class ListView(MasterDetailCrud.ListView):\n        logger = logging.getLogger(__name__)\n        paginate_by = 10\n\n        def take_reuniao_pk(self):\n\n            username = self.request.user.username\n            try:\n                self.logger.debug('user=' + username + '. Tentando obter pk da reuni\u00e3o.')\n                return int(self.request.GET['pk'])\n            except Exception as e:\n                self.logger.error('user=' + username + '. Erro ao obter pk da reuni\u00e3o. Retornado 0. ' + str(e))\n                return 0\n\n        def get_context_data(self, **kwargs):\n            context = super().get_context_data(**kwargs)\n\n            reuniao_pk = self.take_reuniao_pk()\n\n            if reuniao_pk == 0:\n                ultima_reuniao = list(context['reuniao_list'])\n                if len(ultima_reuniao) > 0:\n                    ultimo = ultima_reuniao[-1]\n                    context['reuniao_pk'] = ultimo.pk\n                else:\n                    context['reuniao_pk'] = 0\n            else:\n                context['reuniao_pk'] = reuniao_pk\n\n            context['documentoacessorio_set'] = DocumentoAcessorio.objects.filter(\n                reuniao__pk=context['reuniao_pk']\n            ).order_by('id')\n            return context\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = ReuniaoForm\n\n        def get_initial(self):\n            return {'comissao': self.object.comissao}\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = ReuniaoForm\n\n        def get_initial(self):\n            comissao = Comissao.objects.get(id=self.kwargs['pk'])\n\n            return {'comissao': comissao}\n\n\nclass DocumentoAcessorioCrud(MasterDetailCrud):\n    model = DocumentoAcessorio\n    parent_field = 'reuniao__comissao'\n    public = [RP_DETAIL, ]\n    ListView = None\n    link_return_to_parent_field = True\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['nome', 'tipo', 'data', 'autor', 'arquivo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = DocumentoAcessorioCreateForm\n\n        def get_initial(self):\n            initial = super().get_initial()\n            initial['parent_pk'] = self.kwargs['pk']\n            return initial\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        layout_key = 'DocumentoAcessorioEdit'\n        form_class = DocumentoAcessorioEditForm\n\n    class DeleteView(MasterDetailCrud.DeleteView):\n\n        def delete(self, *args, **kwargs):\n            obj = self.get_object()\n            obj.delete()\n            return HttpResponseRedirect(\n                reverse('sapl.comissoes:reuniao_detail',\n                        kwargs={'pk': obj.reuniao.pk}))\n", "path": "sapl/comissoes/views.py"}], "after_files": [{"content": "import logging\n\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import F\nfrom django.http.response import HttpResponseRedirect\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nfrom django.views.generic import ListView\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import FormMixin\n\nfrom sapl.base.models import AppConfig as AppsAppConfig\nfrom sapl.comissoes.apps import AppConfig\nfrom sapl.comissoes.forms import (ComissaoForm, ComposicaoForm,\n                                  DocumentoAcessorioCreateForm,\n                                  DocumentoAcessorioEditForm,\n                                  ParticipacaoCreateForm, ParticipacaoEditForm,\n                                  PeriodoForm, ReuniaoForm)\nfrom sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,\n                            MasterDetailCrud,\n                            PermissionRequiredForAppCrudMixin)\nfrom sapl.materia.models import MateriaLegislativa, Tramitacao\n\nfrom .models import (CargoComissao, Comissao, Composicao, DocumentoAcessorio,\n                     Participacao, Periodo, Reuniao, TipoComissao)\n\n\ndef pegar_url_composicao(pk):\n    participacao = Participacao.objects.get(id=pk)\n    comp_pk = participacao.composicao.pk\n    url = reverse('sapl.comissoes:composicao_detail', kwargs={'pk': comp_pk})\n    return url\n\n\ndef pegar_url_reuniao(pk):\n    documentoacessorio = DocumentoAcessorio.objects.get(id=pk)\n    r_pk = documentoacessorio.reuniao.pk\n    url = reverse('sapl.comissoes:reuniao_detail', kwargs={'pk': r_pk})\n    return url\n\nCargoCrud = CrudAux.build(CargoComissao, 'cargo_comissao')\n\nTipoComissaoCrud = CrudAux.build(\n    TipoComissao, 'tipo_comissao', list_field_names=[\n        'sigla', 'nome', 'natureza', 'dispositivo_regimental'])\n\n\nclass PeriodoComposicaoCrud(CrudAux):\n    model = Periodo\n\n    class CreateView(CrudAux.CreateView):\n        form_class = PeriodoForm\n\n    class UpdateView(CrudAux.UpdateView):\n        form_class = PeriodoForm\n\n    # class ListView(CrudAux.ListView):\n\n\nclass ParticipacaoCrud(MasterDetailCrud):\n    model = Participacao\n    parent_field = 'composicao__comissao'\n    public = [RP_DETAIL, ]\n    ListView = None\n    link_return_to_parent_field = True\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['composicao', 'parlamentar', 'cargo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = ParticipacaoCreateForm\n\n        def get_initial(self):\n            initial = super().get_initial()\n            initial['parent_pk'] = self.kwargs['pk']\n            return initial\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        layout_key = 'ParticipacaoEdit'\n        form_class = ParticipacaoEditForm\n\n    class DeleteView(MasterDetailCrud.DeleteView):\n\n        def get_success_url(self):\n            composicao_comissao_pk = self.object.composicao.comissao.pk\n            composicao_pk = self.object.composicao.pk\n            return '{}?pk={}'.format(reverse('sapl.comissoes:composicao_list',\n                                             args=[composicao_comissao_pk]),\n                                     composicao_pk)\n\n\nclass ComposicaoCrud(MasterDetailCrud):\n    model = Composicao\n    parent_field = 'comissao'\n    model_set = 'participacao_set'\n    public = [RP_LIST, RP_DETAIL, ]\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = ComposicaoForm\n\n        def get_initial(self):\n            comissao = Comissao.objects.get(id=self.kwargs['pk'])\n            return {'comissao': comissao}\n\n    class ListView(MasterDetailCrud.ListView):\n        logger = logging.getLogger(__name__)\n        template_name = \"comissoes/composicao_list.html\"\n        paginate_by = None\n\n        def take_composicao_pk(self):\n            \n            username = self.request.user.username\n            try:\n                self.logger.debug('user=' + username + '. Tentando obter pk da composi\u00e7\u00e3o.')\n                return int(self.request.GET['pk'])\n            except Exception as e:\n                self.logger.error('user=' + username + '. Erro ao obter pk da composi\u00e7\u00e3o. Retornado 0. ' + str(e))\n                return 0\n\n        def get_context_data(self, **kwargs):\n            context = super().get_context_data(**kwargs)\n\n            composicao_pk = self.take_composicao_pk()\n\n            if composicao_pk == 0:\n                # Composicao eh ordenada por Periodo, que por sua vez esta em\n                # ordem descrescente de data de inicio (issue #1920)\n                ultima_composicao = context['composicao_list'].first()\n                if ultima_composicao:\n                    context['composicao_pk'] = ultima_composicao.pk\n                else:\n                    context['composicao_pk'] = 0\n            else:\n                context['composicao_pk'] = composicao_pk\n\n            context['participacao_set'] = Participacao.objects.filter(\n                composicao__pk=context['composicao_pk']\n            ).order_by('id')\n            return context\n\n\nclass ComissaoCrud(Crud):\n    model = Comissao\n    help_topic = 'modulo_comissoes'\n    public = [RP_LIST, RP_DETAIL, ]\n\n    class BaseMixin(Crud.BaseMixin):\n        list_field_names = ['nome', 'sigla', 'tipo',\n                            'data_criacao', 'data_extincao', 'ativa']\n        ordering = '-ativa', 'sigla'\n\n    class CreateView(Crud.CreateView):\n        form_class = ComissaoForm\n\n        def form_valid(self, form):\n            return super(Crud.CreateView, self).form_valid(form)\n\n    class UpdateView(Crud.UpdateView):\n        form_class = ComissaoForm\n\n        def form_valid(self, form):\n            return super(Crud.UpdateView, self).form_valid(form)\n\n\nclass MateriasTramitacaoListView(ListView):\n    template_name = \"comissoes/materias_em_tramitacao.html\"\n    paginate_by = 10\n\n    def get_queryset(self):\n        # FIXME: Otimizar consulta\n        ts = Tramitacao.objects.order_by(\n            'materia', '-data_tramitacao', '-id').annotate(\n            comissao=F('unidade_tramitacao_destino__comissao')).distinct(\n                'materia').values_list('materia', 'comissao')\n\n        ts = list(filter(lambda x: x[1] == int(self.kwargs['pk']), ts))\n        ts = list(zip(*ts))\n        ts = ts[0] if ts else []\n\n        materias = MateriaLegislativa.objects.filter(\n            pk__in=ts).order_by('tipo', '-ano', '-numero')\n\n        return materias\n\n    def get_context_data(self, **kwargs):\n        context = super(\n            MateriasTramitacaoListView, self).get_context_data(**kwargs)\n        context['object'] = Comissao.objects.get(id=self.kwargs['pk'])\n        context['qtde'] = self.object_list.count()\n        return context\n\n\nclass ReuniaoCrud(MasterDetailCrud):\n    model = Reuniao\n    parent_field = 'comissao'\n    model_set = 'documentoacessorio_set'\n    public = [RP_LIST, RP_DETAIL, ]\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['data', 'nome', 'tema']\n\n    class ListView(MasterDetailCrud.ListView):\n        logger = logging.getLogger(__name__)\n        paginate_by = 10\n\n        def take_reuniao_pk(self):\n\n            username = self.request.user.username\n            try:\n                self.logger.debug('user=' + username + '. Tentando obter pk da reuni\u00e3o.')\n                return int(self.request.GET['pk'])\n            except Exception as e:\n                self.logger.error('user=' + username + '. Erro ao obter pk da reuni\u00e3o. Retornado 0. ' + str(e))\n                return 0\n\n        def get_context_data(self, **kwargs):\n            context = super().get_context_data(**kwargs)\n\n            reuniao_pk = self.take_reuniao_pk()\n\n            if reuniao_pk == 0:\n                ultima_reuniao = list(context['reuniao_list'])\n                if len(ultima_reuniao) > 0:\n                    ultimo = ultima_reuniao[-1]\n                    context['reuniao_pk'] = ultimo.pk\n                else:\n                    context['reuniao_pk'] = 0\n            else:\n                context['reuniao_pk'] = reuniao_pk\n\n            context['documentoacessorio_set'] = DocumentoAcessorio.objects.filter(\n                reuniao__pk=context['reuniao_pk']\n            ).order_by('id')\n            return context\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = ReuniaoForm\n\n        def get_initial(self):\n            return {'comissao': self.object.comissao}\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = ReuniaoForm\n\n        def get_initial(self):\n            comissao = Comissao.objects.get(id=self.kwargs['pk'])\n\n            return {'comissao': comissao}\n\n\nclass DocumentoAcessorioCrud(MasterDetailCrud):\n    model = DocumentoAcessorio\n    parent_field = 'reuniao__comissao'\n    public = [RP_DETAIL, ]\n    ListView = None\n    link_return_to_parent_field = True\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['nome', 'tipo', 'data', 'autor', 'arquivo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = DocumentoAcessorioCreateForm\n\n        def get_initial(self):\n            initial = super().get_initial()\n            initial['parent_pk'] = self.kwargs['pk']\n            return initial\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        layout_key = 'DocumentoAcessorioEdit'\n        form_class = DocumentoAcessorioEditForm\n\n    class DeleteView(MasterDetailCrud.DeleteView):\n\n        def delete(self, *args, **kwargs):\n            obj = self.get_object()\n            obj.delete()\n            return HttpResponseRedirect(\n                reverse('sapl.comissoes:reuniao_detail',\n                        kwargs={'pk': obj.reuniao.pk}))\n", "path": "sapl/comissoes/views.py"}]}