We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Relatório Normas Jurídicas: segundo critério de ordem
O relatório de normas jurídicas tem, por primeiro critério de ordem, a data por ordem decrescente. O segundo critério é o Número, em ordem crescente, que deveria mudar para decrescente.
https://sapl.agudo.rs.leg.br/norma/pesquisar?tipo=12&numero=&ano=2018&data_0=&data_1=&data_publicacao_0=&data_publicacao_1=&ementa=&assuntos=
![captura de tela de 2018-08-02 08-30-28](https://user-images.githubusercontent.com/19169882/43581175-6fa4b8ca-962e-11e8-8ff0-5281b41c1888.png)


--- 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/norma/views.py`
Content:
```
1 
2 import re
3 import weasyprint
4 from django.contrib.auth.mixins import PermissionRequiredMixin
5 from django.core.exceptions import ObjectDoesNotExist
6 from django.core.urlresolvers import reverse
7 from django.http import HttpResponse, JsonResponse
8 from django.template import RequestContext, loader
9 from django.utils import timezone
10 from django.utils.translation import ugettext_lazy as _
11 from django.views.generic import TemplateView, UpdateView
12 from django.views.generic.base import RedirectView
13 from django.views.generic.edit import FormView
14 from django_filters.views import FilterView
15 
16 from sapl.base.models import AppConfig
17 from sapl.compilacao.views import IntegracaoTaView
18 from sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,
19                             MasterDetailCrud, make_pagination)
20 from sapl.utils import show_results_filter_set
21 
22 from .forms import (NormaFilterSet, NormaJuridicaForm,
23                     NormaPesquisaSimplesForm, NormaRelacionadaForm)
24 from .models import (AssuntoNorma, NormaJuridica, NormaRelacionada,
25                      TipoNormaJuridica, TipoVinculoNormaJuridica)
26 
27 # LegislacaoCitadaCrud = Crud.build(LegislacaoCitada, '')
28 AssuntoNormaCrud = CrudAux.build(AssuntoNorma, 'assunto_norma_juridica',
29                                  list_field_names=['assunto', 'descricao'])
30 
31 
32 TipoNormaCrud = CrudAux.build(
33     TipoNormaJuridica, 'tipo_norma_juridica',
34     list_field_names=['sigla', 'descricao', 'equivalente_lexml'])
35 TipoVinculoNormaJuridicaCrud = CrudAux.build(
36     TipoVinculoNormaJuridica, '',
37     list_field_names=['sigla', 'descricao_ativa', 'descricao_passiva'])
38 
39 
40 class NormaRelacionadaCrud(MasterDetailCrud):
41     model = NormaRelacionada
42     parent_field = 'norma_principal'
43     help_topic = 'norma_juridica'
44 
45     class BaseMixin(MasterDetailCrud.BaseMixin):
46         list_field_names = ['norma_relacionada', 'tipo_vinculo']
47 
48     class CreateView(MasterDetailCrud.CreateView):
49         form_class = NormaRelacionadaForm
50 
51     class UpdateView(MasterDetailCrud.UpdateView):
52         form_class = NormaRelacionadaForm
53 
54         def get_initial(self):
55             initial = super(UpdateView, self).get_initial()
56             initial['tipo'] = self.object.norma_relacionada.tipo.id
57             initial['numero'] = self.object.norma_relacionada.numero
58             initial['ano'] = self.object.norma_relacionada.ano
59             initial['ementa'] = self.object.norma_relacionada.ementa
60             return initial
61 
62     class DetailView(MasterDetailCrud.DetailView):
63 
64         layout_key = 'NormaRelacionadaDetail'
65 
66 
67 class NormaPesquisaView(FilterView):
68     model = NormaJuridica
69     filterset_class = NormaFilterSet
70     paginate_by = 10
71 
72     def get_queryset(self):
73         qs = super().get_queryset()
74 
75         qs.select_related('tipo', 'materia')
76 
77         return qs
78 
79     def get_context_data(self, **kwargs):
80         context = super(NormaPesquisaView, self).get_context_data(**kwargs)
81 
82         context['title'] = _('Pesquisar Norma Jurídica')
83 
84         qr = self.request.GET.copy()
85 
86         if 'page' in qr:
87             del qr['page']
88 
89         paginator = context['paginator']
90         page_obj = context['page_obj']
91 
92         context['page_range'] = make_pagination(
93             page_obj.number, paginator.num_pages)
94 
95         context['filter_url'] = ('&' + qr.urlencode()) if len(qr) > 0 else ''
96 
97         context['show_results'] = show_results_filter_set(qr)
98 
99         return context
100 
101 
102 class NormaTaView(IntegracaoTaView):
103     model = NormaJuridica
104     model_type_foreignkey = TipoNormaJuridica
105     map_fields = {
106         'data': 'data',
107         'ementa': 'ementa',
108         'observacao': 'observacao',
109         'numero': 'numero',
110         'ano': 'ano',
111     }
112 
113     map_funcs = {
114         'publicacao_func': True
115     }
116 
117     def get(self, request, *args, **kwargs):
118         """
119         Para manter a app compilacao isolada das outras aplicações,
120         este get foi implementado para tratar uma prerrogativa externa
121         de usuário.
122         """
123         if AppConfig.attr('texto_articulado_norma'):
124             return IntegracaoTaView.get(self, request, *args, **kwargs)
125         else:
126             return self.get_redirect_deactivated()
127 
128 
129 class NormaCrud(Crud):
130     model = NormaJuridica
131     help_topic = 'norma_juridica'
132     public = [RP_LIST, RP_DETAIL]
133 
134     class BaseMixin(Crud.BaseMixin):
135         list_field_names = ['tipo', 'numero', 'ano', 'ementa']
136 
137         list_url = ''
138 
139         @property
140         def search_url(self):
141             namespace = self.model._meta.app_config.name
142             return reverse('%s:%s' % (namespace, 'norma_pesquisa'))
143 
144     class DetailView(Crud.DetailView):
145         pass
146 
147     class DeleteView(Crud.DeleteView):
148 
149         def get_success_url(self):
150             return self.search_url
151 
152     class CreateView(Crud.CreateView):
153         form_class = NormaJuridicaForm
154 
155         @property
156         def cancel_url(self):
157             return self.search_url
158 
159         layout_key = 'NormaJuridicaCreate'
160 
161     class ListView(Crud.ListView, RedirectView):
162 
163         def get_redirect_url(self, *args, **kwargs):
164             namespace = self.model._meta.app_config.name
165             return reverse('%s:%s' % (namespace, 'norma_pesquisa'))
166 
167         def get(self, request, *args, **kwargs):
168             return RedirectView.get(self, request, *args, **kwargs)
169 
170     class UpdateView(Crud.UpdateView):
171         form_class = NormaJuridicaForm
172 
173         layout_key = 'NormaJuridicaCreate'
174 
175         def get_initial(self):
176             initial = super(UpdateView, self).get_initial()
177             norma = NormaJuridica.objects.get(id=self.kwargs['pk'])
178             if norma.materia:
179                 initial['tipo_materia'] = norma.materia.tipo
180                 initial['ano_materia'] = norma.materia.ano
181                 initial['numero_materia'] = norma.materia.numero
182             return initial
183 
184 
185 def recuperar_norma(request):
186     tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])
187     numero = request.GET['numero']
188     ano = request.GET['ano']
189 
190     try:
191         norma = NormaJuridica.objects.get(tipo=tipo,
192                                           ano=ano,
193                                           numero=numero)
194         response = JsonResponse({'ementa': norma.ementa,
195                                  'id': norma.id})
196     except ObjectDoesNotExist:
197         response = JsonResponse({'ementa': '', 'id': 0})
198 
199     return response
200 
201 
202 def recuperar_numero_norma(request):
203     tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])
204     ano = request.GET.get('ano', '')
205     param = {'tipo': tipo}
206     param['ano'] = ano if ano else timezone.now().year
207     norma = NormaJuridica.objects.filter(**param).order_by(
208             'tipo', 'ano').values_list('numero', 'ano').last()
209     if norma:
210         response = JsonResponse({'numero': int(re.sub("[^0-9].*", '', norma[0])) + 1,
211                                  'ano': norma[1]})
212     else:
213         response = JsonResponse(
214             {'numero': 1, 'ano': ano})
215 
216     return response
217 
218 
219 class ImpressosView(PermissionRequiredMixin, TemplateView):
220     template_name = 'materia/impressos/impressos.html'
221     permission_required = ('materia.can_access_impressos', )
222 
223 
224 def gerar_pdf_impressos(request, context, template_name):
225     template = loader.get_template(template_name)
226     html = template.render(RequestContext(request, context))
227     pdf = weasyprint.HTML(string=html, base_url=request.build_absolute_uri()
228                           ).write_pdf()
229 
230     response = HttpResponse(pdf, content_type='application/pdf')
231     response['Content-Disposition'] = (
232         'inline; filename="relatorio_impressos.pdf"')
233     response['Content-Transfer-Encoding'] = 'binary'
234 
235     return response
236 
237 
238 class NormaPesquisaSimplesView(PermissionRequiredMixin, FormView):
239     form_class = NormaPesquisaSimplesForm
240     template_name = 'materia/impressos/norma.html'
241     permission_required = ('materia.can_access_impressos', )
242 
243     def form_valid(self, form):
244         normas = NormaJuridica.objects.all().order_by(
245             'numero')
246         template_norma = 'materia/impressos/normas_pdf.html'
247 
248         titulo = form.cleaned_data['titulo']
249 
250         if form.cleaned_data['tipo_norma']:
251             normas = normas.filter(tipo=form.cleaned_data['tipo_norma'])
252 
253         if form.cleaned_data['data_inicial']:
254             normas = normas.filter(
255                 data__gte=form.cleaned_data['data_inicial'],
256                 data__lte=form.cleaned_data['data_final'])
257 
258         qtd_resultados = len(normas)
259         if qtd_resultados > 2000:
260             normas = normas[:2000]
261 
262         context = {'quantidade': qtd_resultados,
263                    'titulo': titulo,
264                    'normas': normas}
265 
266         return gerar_pdf_impressos(self.request, context, template_norma)
267
```
--- 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/norma/views.py b/sapl/norma/views.py
--- a/sapl/norma/views.py
+++ b/sapl/norma/views.py
@@ -72,7 +72,7 @@
     def get_queryset(self):
         qs = super().get_queryset()
 
-        qs.select_related('tipo', 'materia')
+        qs = qs.extra({'norma_i': "CAST(regexp_replace(numero,'[^0-9]','', 'g') AS INTEGER)", 'norma_letra': "regexp_replace(numero,'[^a-zA-Z]','', 'g')"}).order_by('-data', '-norma_i', '-norma_letra')
 
         return qs

{"golden_diff": "diff --git a/sapl/norma/views.py b/sapl/norma/views.py\n--- a/sapl/norma/views.py\n+++ b/sapl/norma/views.py\n@@ -72,7 +72,7 @@\n     def get_queryset(self):\n         qs = super().get_queryset()\n \n-        qs.select_related('tipo', 'materia')\n+        qs = qs.extra({'norma_i': \"CAST(regexp_replace(numero,'[^0-9]','', 'g') AS INTEGER)\", 'norma_letra': \"regexp_replace(numero,'[^a-zA-Z]','', 'g')\"}).order_by('-data', '-norma_i', '-norma_letra')\n \n         return qs\n", "issue": "Relat\u00f3rio Normas Jur\u00eddicas: segundo crit\u00e9rio de ordem\nO relat\u00f3rio de normas jur\u00eddicas tem, por primeiro crit\u00e9rio de ordem, a data por ordem decrescente. O segundo crit\u00e9rio \u00e9 o N\u00famero, em ordem crescente, que deveria mudar para decrescente.\r\nhttps://sapl.agudo.rs.leg.br/norma/pesquisar?tipo=12&numero=&ano=2018&data_0=&data_1=&data_publicacao_0=&data_publicacao_1=&ementa=&assuntos=\r\n![captura de tela de 2018-08-02 08-30-28](https://user-images.githubusercontent.com/19169882/43581175-6fa4b8ca-962e-11e8-8ff0-5281b41c1888.png)\r\n\n", "before_files": [{"content": "\nimport re\nimport weasyprint\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, JsonResponse\nfrom django.template import RequestContext, loader\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import TemplateView, UpdateView\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic.edit import FormView\nfrom django_filters.views import FilterView\n\nfrom sapl.base.models import AppConfig\nfrom sapl.compilacao.views import IntegracaoTaView\nfrom sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,\n                            MasterDetailCrud, make_pagination)\nfrom sapl.utils import show_results_filter_set\n\nfrom .forms import (NormaFilterSet, NormaJuridicaForm,\n                    NormaPesquisaSimplesForm, NormaRelacionadaForm)\nfrom .models import (AssuntoNorma, NormaJuridica, NormaRelacionada,\n                     TipoNormaJuridica, TipoVinculoNormaJuridica)\n\n# LegislacaoCitadaCrud = Crud.build(LegislacaoCitada, '')\nAssuntoNormaCrud = CrudAux.build(AssuntoNorma, 'assunto_norma_juridica',\n                                 list_field_names=['assunto', 'descricao'])\n\n\nTipoNormaCrud = CrudAux.build(\n    TipoNormaJuridica, 'tipo_norma_juridica',\n    list_field_names=['sigla', 'descricao', 'equivalente_lexml'])\nTipoVinculoNormaJuridicaCrud = CrudAux.build(\n    TipoVinculoNormaJuridica, '',\n    list_field_names=['sigla', 'descricao_ativa', 'descricao_passiva'])\n\n\nclass NormaRelacionadaCrud(MasterDetailCrud):\n    model = NormaRelacionada\n    parent_field = 'norma_principal'\n    help_topic = 'norma_juridica'\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['norma_relacionada', 'tipo_vinculo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = NormaRelacionadaForm\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = NormaRelacionadaForm\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            initial['tipo'] = self.object.norma_relacionada.tipo.id\n            initial['numero'] = self.object.norma_relacionada.numero\n            initial['ano'] = self.object.norma_relacionada.ano\n            initial['ementa'] = self.object.norma_relacionada.ementa\n            return initial\n\n    class DetailView(MasterDetailCrud.DetailView):\n\n        layout_key = 'NormaRelacionadaDetail'\n\n\nclass NormaPesquisaView(FilterView):\n    model = NormaJuridica\n    filterset_class = NormaFilterSet\n    paginate_by = 10\n\n    def get_queryset(self):\n        qs = super().get_queryset()\n\n        qs.select_related('tipo', 'materia')\n\n        return qs\n\n    def get_context_data(self, **kwargs):\n        context = super(NormaPesquisaView, self).get_context_data(**kwargs)\n\n        context['title'] = _('Pesquisar Norma Jur\u00eddica')\n\n        qr = self.request.GET.copy()\n\n        if 'page' in qr:\n            del qr['page']\n\n        paginator = context['paginator']\n        page_obj = context['page_obj']\n\n        context['page_range'] = make_pagination(\n            page_obj.number, paginator.num_pages)\n\n        context['filter_url'] = ('&' + qr.urlencode()) if len(qr) > 0 else ''\n\n        context['show_results'] = show_results_filter_set(qr)\n\n        return context\n\n\nclass NormaTaView(IntegracaoTaView):\n    model = NormaJuridica\n    model_type_foreignkey = TipoNormaJuridica\n    map_fields = {\n        'data': 'data',\n        'ementa': 'ementa',\n        'observacao': 'observacao',\n        'numero': 'numero',\n        'ano': 'ano',\n    }\n\n    map_funcs = {\n        'publicacao_func': True\n    }\n\n    def get(self, request, *args, **kwargs):\n        \"\"\"\n        Para manter a app compilacao isolada das outras aplica\u00e7\u00f5es,\n        este get foi implementado para tratar uma prerrogativa externa\n        de usu\u00e1rio.\n        \"\"\"\n        if AppConfig.attr('texto_articulado_norma'):\n            return IntegracaoTaView.get(self, request, *args, **kwargs)\n        else:\n            return self.get_redirect_deactivated()\n\n\nclass NormaCrud(Crud):\n    model = NormaJuridica\n    help_topic = 'norma_juridica'\n    public = [RP_LIST, RP_DETAIL]\n\n    class BaseMixin(Crud.BaseMixin):\n        list_field_names = ['tipo', 'numero', 'ano', 'ementa']\n\n        list_url = ''\n\n        @property\n        def search_url(self):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n    class DetailView(Crud.DetailView):\n        pass\n\n    class DeleteView(Crud.DeleteView):\n\n        def get_success_url(self):\n            return self.search_url\n\n    class CreateView(Crud.CreateView):\n        form_class = NormaJuridicaForm\n\n        @property\n        def cancel_url(self):\n            return self.search_url\n\n        layout_key = 'NormaJuridicaCreate'\n\n    class ListView(Crud.ListView, RedirectView):\n\n        def get_redirect_url(self, *args, **kwargs):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n        def get(self, request, *args, **kwargs):\n            return RedirectView.get(self, request, *args, **kwargs)\n\n    class UpdateView(Crud.UpdateView):\n        form_class = NormaJuridicaForm\n\n        layout_key = 'NormaJuridicaCreate'\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            norma = NormaJuridica.objects.get(id=self.kwargs['pk'])\n            if norma.materia:\n                initial['tipo_materia'] = norma.materia.tipo\n                initial['ano_materia'] = norma.materia.ano\n                initial['numero_materia'] = norma.materia.numero\n            return initial\n\n\ndef recuperar_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    numero = request.GET['numero']\n    ano = request.GET['ano']\n\n    try:\n        norma = NormaJuridica.objects.get(tipo=tipo,\n                                          ano=ano,\n                                          numero=numero)\n        response = JsonResponse({'ementa': norma.ementa,\n                                 'id': norma.id})\n    except ObjectDoesNotExist:\n        response = JsonResponse({'ementa': '', 'id': 0})\n\n    return response\n\n\ndef recuperar_numero_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    ano = request.GET.get('ano', '')\n    param = {'tipo': tipo}\n    param['ano'] = ano if ano else timezone.now().year\n    norma = NormaJuridica.objects.filter(**param).order_by(\n            'tipo', 'ano').values_list('numero', 'ano').last()\n    if norma:\n        response = JsonResponse({'numero': int(re.sub(\"[^0-9].*\", '', norma[0])) + 1,\n                                 'ano': norma[1]})\n    else:\n        response = JsonResponse(\n            {'numero': 1, 'ano': ano})\n\n    return response\n\n\nclass ImpressosView(PermissionRequiredMixin, TemplateView):\n    template_name = 'materia/impressos/impressos.html'\n    permission_required = ('materia.can_access_impressos', )\n\n\ndef gerar_pdf_impressos(request, context, template_name):\n    template = loader.get_template(template_name)\n    html = template.render(RequestContext(request, context))\n    pdf = weasyprint.HTML(string=html, base_url=request.build_absolute_uri()\n                          ).write_pdf()\n\n    response = HttpResponse(pdf, content_type='application/pdf')\n    response['Content-Disposition'] = (\n        'inline; filename=\"relatorio_impressos.pdf\"')\n    response['Content-Transfer-Encoding'] = 'binary'\n\n    return response\n\n\nclass NormaPesquisaSimplesView(PermissionRequiredMixin, FormView):\n    form_class = NormaPesquisaSimplesForm\n    template_name = 'materia/impressos/norma.html'\n    permission_required = ('materia.can_access_impressos', )\n\n    def form_valid(self, form):\n        normas = NormaJuridica.objects.all().order_by(\n            'numero')\n        template_norma = 'materia/impressos/normas_pdf.html'\n\n        titulo = form.cleaned_data['titulo']\n\n        if form.cleaned_data['tipo_norma']:\n            normas = normas.filter(tipo=form.cleaned_data['tipo_norma'])\n\n        if form.cleaned_data['data_inicial']:\n            normas = normas.filter(\n                data__gte=form.cleaned_data['data_inicial'],\n                data__lte=form.cleaned_data['data_final'])\n\n        qtd_resultados = len(normas)\n        if qtd_resultados > 2000:\n            normas = normas[:2000]\n\n        context = {'quantidade': qtd_resultados,\n                   'titulo': titulo,\n                   'normas': normas}\n\n        return gerar_pdf_impressos(self.request, context, template_norma)\n", "path": "sapl/norma/views.py"}], "after_files": [{"content": "\nimport re\nimport weasyprint\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, JsonResponse\nfrom django.template import RequestContext, loader\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import TemplateView, UpdateView\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic.edit import FormView\nfrom django_filters.views import FilterView\n\nfrom sapl.base.models import AppConfig\nfrom sapl.compilacao.views import IntegracaoTaView\nfrom sapl.crud.base import (RP_DETAIL, RP_LIST, Crud, CrudAux,\n                            MasterDetailCrud, make_pagination)\nfrom sapl.utils import show_results_filter_set\n\nfrom .forms import (NormaFilterSet, NormaJuridicaForm,\n                    NormaPesquisaSimplesForm, NormaRelacionadaForm)\nfrom .models import (AssuntoNorma, NormaJuridica, NormaRelacionada,\n                     TipoNormaJuridica, TipoVinculoNormaJuridica)\n\n# LegislacaoCitadaCrud = Crud.build(LegislacaoCitada, '')\nAssuntoNormaCrud = CrudAux.build(AssuntoNorma, 'assunto_norma_juridica',\n                                 list_field_names=['assunto', 'descricao'])\n\n\nTipoNormaCrud = CrudAux.build(\n    TipoNormaJuridica, 'tipo_norma_juridica',\n    list_field_names=['sigla', 'descricao', 'equivalente_lexml'])\nTipoVinculoNormaJuridicaCrud = CrudAux.build(\n    TipoVinculoNormaJuridica, '',\n    list_field_names=['sigla', 'descricao_ativa', 'descricao_passiva'])\n\n\nclass NormaRelacionadaCrud(MasterDetailCrud):\n    model = NormaRelacionada\n    parent_field = 'norma_principal'\n    help_topic = 'norma_juridica'\n\n    class BaseMixin(MasterDetailCrud.BaseMixin):\n        list_field_names = ['norma_relacionada', 'tipo_vinculo']\n\n    class CreateView(MasterDetailCrud.CreateView):\n        form_class = NormaRelacionadaForm\n\n    class UpdateView(MasterDetailCrud.UpdateView):\n        form_class = NormaRelacionadaForm\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            initial['tipo'] = self.object.norma_relacionada.tipo.id\n            initial['numero'] = self.object.norma_relacionada.numero\n            initial['ano'] = self.object.norma_relacionada.ano\n            initial['ementa'] = self.object.norma_relacionada.ementa\n            return initial\n\n    class DetailView(MasterDetailCrud.DetailView):\n\n        layout_key = 'NormaRelacionadaDetail'\n\n\nclass NormaPesquisaView(FilterView):\n    model = NormaJuridica\n    filterset_class = NormaFilterSet\n    paginate_by = 10\n\n    def get_queryset(self):\n        qs = super().get_queryset()\n\n        qs = qs.extra({'norma_i': \"CAST(regexp_replace(numero,'[^0-9]','', 'g') AS INTEGER)\", 'norma_letra': \"regexp_replace(numero,'[^a-zA-Z]','', 'g')\"}).order_by('-data', '-norma_i', '-norma_letra')\n\n        return qs\n\n    def get_context_data(self, **kwargs):\n        context = super(NormaPesquisaView, self).get_context_data(**kwargs)\n\n        context['title'] = _('Pesquisar Norma Jur\u00eddica')\n\n        qr = self.request.GET.copy()\n\n        if 'page' in qr:\n            del qr['page']\n\n        paginator = context['paginator']\n        page_obj = context['page_obj']\n\n        context['page_range'] = make_pagination(\n            page_obj.number, paginator.num_pages)\n\n        context['filter_url'] = ('&' + qr.urlencode()) if len(qr) > 0 else ''\n\n        context['show_results'] = show_results_filter_set(qr)\n\n        return context\n\n\nclass NormaTaView(IntegracaoTaView):\n    model = NormaJuridica\n    model_type_foreignkey = TipoNormaJuridica\n    map_fields = {\n        'data': 'data',\n        'ementa': 'ementa',\n        'observacao': 'observacao',\n        'numero': 'numero',\n        'ano': 'ano',\n    }\n\n    map_funcs = {\n        'publicacao_func': True\n    }\n\n    def get(self, request, *args, **kwargs):\n        \"\"\"\n        Para manter a app compilacao isolada das outras aplica\u00e7\u00f5es,\n        este get foi implementado para tratar uma prerrogativa externa\n        de usu\u00e1rio.\n        \"\"\"\n        if AppConfig.attr('texto_articulado_norma'):\n            return IntegracaoTaView.get(self, request, *args, **kwargs)\n        else:\n            return self.get_redirect_deactivated()\n\n\nclass NormaCrud(Crud):\n    model = NormaJuridica\n    help_topic = 'norma_juridica'\n    public = [RP_LIST, RP_DETAIL]\n\n    class BaseMixin(Crud.BaseMixin):\n        list_field_names = ['tipo', 'numero', 'ano', 'ementa']\n\n        list_url = ''\n\n        @property\n        def search_url(self):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n    class DetailView(Crud.DetailView):\n        pass\n\n    class DeleteView(Crud.DeleteView):\n\n        def get_success_url(self):\n            return self.search_url\n\n    class CreateView(Crud.CreateView):\n        form_class = NormaJuridicaForm\n\n        @property\n        def cancel_url(self):\n            return self.search_url\n\n        layout_key = 'NormaJuridicaCreate'\n\n    class ListView(Crud.ListView, RedirectView):\n\n        def get_redirect_url(self, *args, **kwargs):\n            namespace = self.model._meta.app_config.name\n            return reverse('%s:%s' % (namespace, 'norma_pesquisa'))\n\n        def get(self, request, *args, **kwargs):\n            return RedirectView.get(self, request, *args, **kwargs)\n\n    class UpdateView(Crud.UpdateView):\n        form_class = NormaJuridicaForm\n\n        layout_key = 'NormaJuridicaCreate'\n\n        def get_initial(self):\n            initial = super(UpdateView, self).get_initial()\n            norma = NormaJuridica.objects.get(id=self.kwargs['pk'])\n            if norma.materia:\n                initial['tipo_materia'] = norma.materia.tipo\n                initial['ano_materia'] = norma.materia.ano\n                initial['numero_materia'] = norma.materia.numero\n            return initial\n\n\ndef recuperar_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    numero = request.GET['numero']\n    ano = request.GET['ano']\n\n    try:\n        norma = NormaJuridica.objects.get(tipo=tipo,\n                                          ano=ano,\n                                          numero=numero)\n        response = JsonResponse({'ementa': norma.ementa,\n                                 'id': norma.id})\n    except ObjectDoesNotExist:\n        response = JsonResponse({'ementa': '', 'id': 0})\n\n    return response\n\n\ndef recuperar_numero_norma(request):\n    tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n    ano = request.GET.get('ano', '')\n    param = {'tipo': tipo}\n    param['ano'] = ano if ano else timezone.now().year\n    norma = NormaJuridica.objects.filter(**param).order_by(\n            'tipo', 'ano').values_list('numero', 'ano').last()\n    if norma:\n        response = JsonResponse({'numero': int(re.sub(\"[^0-9].*\", '', norma[0])) + 1,\n                                 'ano': norma[1]})\n    else:\n        response = JsonResponse(\n            {'numero': 1, 'ano': ano})\n\n    return response\n\n\nclass ImpressosView(PermissionRequiredMixin, TemplateView):\n    template_name = 'materia/impressos/impressos.html'\n    permission_required = ('materia.can_access_impressos', )\n\n\ndef gerar_pdf_impressos(request, context, template_name):\n    template = loader.get_template(template_name)\n    html = template.render(RequestContext(request, context))\n    pdf = weasyprint.HTML(string=html, base_url=request.build_absolute_uri()\n                          ).write_pdf()\n\n    response = HttpResponse(pdf, content_type='application/pdf')\n    response['Content-Disposition'] = (\n        'inline; filename=\"relatorio_impressos.pdf\"')\n    response['Content-Transfer-Encoding'] = 'binary'\n\n    return response\n\n\nclass NormaPesquisaSimplesView(PermissionRequiredMixin, FormView):\n    form_class = NormaPesquisaSimplesForm\n    template_name = 'materia/impressos/norma.html'\n    permission_required = ('materia.can_access_impressos', )\n\n    def form_valid(self, form):\n        normas = NormaJuridica.objects.all().order_by(\n            'numero')\n        template_norma = 'materia/impressos/normas_pdf.html'\n\n        titulo = form.cleaned_data['titulo']\n\n        if form.cleaned_data['tipo_norma']:\n            normas = normas.filter(tipo=form.cleaned_data['tipo_norma'])\n\n        if form.cleaned_data['data_inicial']:\n            normas = normas.filter(\n                data__gte=form.cleaned_data['data_inicial'],\n                data__lte=form.cleaned_data['data_final'])\n\n        qtd_resultados = len(normas)\n        if qtd_resultados > 2000:\n            normas = normas[:2000]\n\n        context = {'quantidade': qtd_resultados,\n                   'titulo': titulo,\n                   'normas': normas}\n\n        return gerar_pdf_impressos(self.request, context, template_norma)\n", "path": "sapl/norma/views.py"}]}