We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Auto-numeração de Norma Jurídica
Retirado do tíquete nº 132457
"Bom dia,
Achei muito útil a funcionalidade de numeração automática das normas jurídicas no SAPL 3.1
Outra novidade que gostei muito é a aceitação de leis com letra no final, do tipo "lei 2133A"
Porém, quando insiro alguma lei com letra, a auto-numeração das leis seguintes deixa de funcionar. 
Peço então que, por gentileza, revisem esse problema. 
Atenciosamente,
Marcos F. Scher."

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

{"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@@ -1,4 +1,5 @@\n \n+import re\n import weasyprint\n from django.contrib.auth.mixins import PermissionRequiredMixin\n from django.core.exceptions import ObjectDoesNotExist\n@@ -201,14 +202,12 @@\n def recuperar_numero_norma(request):\n     tipo = TipoNormaJuridica.objects.get(pk=request.GET['tipo'])\n     ano = request.GET.get('ano', '')\n-\n     param = {'tipo': tipo}\n     param['ano'] = ano if ano else timezone.now().year\n-    norma = NormaJuridica.objects.filter(**param).extra(\n-            {'numero_id': \"CAST(numero as INTEGER)\"}).order_by(\n-            'tipo', 'ano','numero_id').values_list('numero', 'ano').last()\n+    norma = NormaJuridica.objects.filter(**param).order_by(\n+            'tipo', 'ano').values_list('numero', 'ano').last()\n     if norma:\n-        response = JsonResponse({'numero': int(norma[0]) + 1,\n+        response = JsonResponse({'numero': int(re.sub(\"[^0-9].*\", '', norma[0])) + 1,\n                                  'ano': norma[1]})\n     else:\n         response = JsonResponse(\n", "issue": "Auto-numera\u00e7\u00e3o de Norma Jur\u00eddica\nRetirado do t\u00edquete n\u00ba 132457\r\n\"Bom dia,\r\nAchei muito \u00fatil a funcionalidade de numera\u00e7\u00e3o autom\u00e1tica das normas jur\u00eddicas no SAPL 3.1\r\nOutra novidade que gostei muito \u00e9 a aceita\u00e7\u00e3o de leis com letra no final, do tipo \"lei 2133A\"\r\nPor\u00e9m, quando insiro alguma lei com letra, a auto-numera\u00e7\u00e3o das leis seguintes deixa de funcionar. \r\nPe\u00e7o ent\u00e3o que, por gentileza, revisem esse problema. \r\nAtenciosamente,\r\nMarcos F. Scher.\"\n", "before_files": [{"content": "\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\n    param = {'tipo': tipo}\n    param['ano'] = ano if ano else timezone.now().year\n    norma = NormaJuridica.objects.filter(**param).extra(\n            {'numero_id': \"CAST(numero as INTEGER)\"}).order_by(\n            'tipo', 'ano','numero_id').values_list('numero', 'ano').last()\n    if norma:\n        response = JsonResponse({'numero': int(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.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"}]}