Repository: interlegis/sapl

Issue:
Erro ao protocolar matéria
Ao protocolar uma matéria, marcando o botão Vincular a matéria existente, não, acontece o seguinte erro

![image](https://user-images.githubusercontent.com/13314947/37046463-3491ff10-2147-11e8-9b73-0f84871a56a3.png)



![image](https://user-images.githubusercontent.com/13314947/37046486-43389d80-2147-11e8-853d-9002817c91b9.png)



Discussion:
O erro acontece a partir deste commit
https://github.com/interlegis/sapl/commit/5efba8a78881b0a8e6a35066abfdacc6d54199ad
Nessa pagina amarela tem um link com o título "Switch to Copy and Paste". Clique nesse link. Vai abrir uma caixa de texto. Copie todo o conteúdo dessa caixa de texto e cole como comentário aqui.


Environment:


Request Method: POST
Request URL: http://saplbeta.camarabento.rs.gov.br/protocoloadm/protocolar-mat

Django Version: 1.9.13
Python Version: 3.5.2
Installed Applications:
('django_admin_bootstrapped',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_extensions',
 'djangobower',
 'bootstrap3',
 'crispy_forms',
 'easy_thumbnails',
 'image_cropping',
 'floppyforms',
 'haystack',
 'sass_processor',
 'rest_framework',
 'reversion',
 'whoosh',
 'sapl.base',
 'sapl.crud',
 'sapl.parlamentares',
 'sapl.comissoes',
 'sapl.materia',
 'sapl.norma',
 'sapl.sessao',
 'sapl.lexml',
 'sapl.painel',
 'sapl.protocoloadm',
 'sapl.redireciona_urls',
 'sapl.compilacao',
 'sapl.api',
 'sapl.rules',
 'debug_toolbar',
 'rest_framework_docs')
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
 'reversion.middleware.RevisionMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')



Traceback:

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/contrib/auth/mixins.py" in dispatch
  92.         return super(PermissionRequiredMixin, self).dispatch(request, *args, **kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/views/generic/edit.py" in post
  256.         return super(BaseCreateView, self).post(request, *args, **kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/views/generic/edit.py" in post
  222.             return self.form_valid(form)

File "/var/interlegis/sapl/sapl/protocoloadm/views.py" in form_valid
  474.                                                  tipo=data['tipo_materia'])

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
  122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/query.py" in get
  378.         clone = self.filter(*args, **kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/query.py" in filter
  790.         return self._filter_or_exclude(False, *args, **kwargs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/query.py" in _filter_or_exclude
  808.             clone.query.add_q(Q(*args, **kwargs))

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/sql/query.py" in add_q
  1243.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/sql/query.py" in _add_q
  1269.                     allow_joins=allow_joins, split_subq=split_subq,

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/sql/query.py" in build_filter
  1203.             condition = self.build_lookup(lookups, col, value)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/sql/query.py" in build_lookup
  1099.                 return final_lookup(lhs, rhs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/lookups.py" in __init__
  19.         self.rhs = self.get_prep_lookup()

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/lookups.py" in get_prep_lookup
  57.         return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
  1860.         return super(IntegerField, self).get_prep_lookup(lookup_type, value)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
  744.             return self.get_prep_value(value)

File "/var/interlegis/.virtualenvs/sapl/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  1854.         return int(value)

Exception Type: ValueError at /protocoloadm/protocolar-mat
Exception Value: invalid literal for int() with base 10: ''

Estranho. Testamos essa tela...

Até que possamos resolver digite `git revert ba4022a28fdb53e76f75361d0566ee1542bfe819` . Isso vai te jogar pro commit antes desse bug pra usar a tela enquanto analisamos o que houve.

Resolving patch:
diff --git a/sapl/protocoloadm/forms.py b/sapl/protocoloadm/forms.py
--- a/sapl/protocoloadm/forms.py
+++ b/sapl/protocoloadm/forms.py
@@ -372,7 +372,8 @@ class ProtocoloMateriaForm(ModelForm):
 
     vincular_materia = forms.ChoiceField(label=_('Vincular a matéria existente?'),
                                          widget=forms.RadioSelect(),
-                                         choices= YES_NO_CHOICES)
+                                         choices= YES_NO_CHOICES,
+                                         initial=False)
 
     numero_paginas = forms.CharField(label=_('Núm. Páginas'), required=True)
 
diff --git a/sapl/protocoloadm/views.py b/sapl/protocoloadm/views.py
--- a/sapl/protocoloadm/views.py
+++ b/sapl/protocoloadm/views.py
@@ -287,10 +287,8 @@ def form_valid(self, form):
             messages.add_message(self.request, messages.ERROR, msg)
             return self.render_to_response(self.get_context_data())
 
-        tipo = form.cleaned_data['tipo_documento']
-
         if numeracao == 'A':
-            numero = DocumentoAdministrativo.objects.filter(
+            numero = Protocolo.objects.filter(
                 ano=timezone.now().year, tipo=tipo).aggregate(Max('numero'))
         elif numeracao == 'L':
             legislatura = Legislatura.objects.filter(
@@ -298,13 +296,12 @@ def form_valid(self, form):
                 data_fim__year__gte=timezone.now().year).first()
             data_inicio = legislatura.data_inicio
             data_fim = legislatura.data_fim
-            numero = DocumentoAdministrativo.objects.filter(
+            numero = Protocolo.objects.filter(
                 data__gte=data_inicio,
-                data__lte=data_fim,
-                tipo=tipo).aggregate(
+                data__lte=data_fim).aggregate(
                 Max('numero'))
         elif numeracao == 'U':
-            numero = DocumentoAdministrativo.objects.filter(tipo=tipo).aggregate(Max('numero'))
+            numero = Protocolo.objects.filter().aggregate(Max('numero'))
 
         protocolo.tipo_processo = '0'  # TODO validar o significado
         protocolo.anulado = False
@@ -428,14 +425,8 @@ def form_valid(self, form):
             messages.add_message(self.request, messages.ERROR, msg)
             return self.render_to_response(self.get_context_data())
 
-        # Se TipoMateriaLegislativa tem sequencia própria,
-        # então sobreescreve a sequência global
-        tipo = form.cleaned_data['tipo_materia']
-        if tipo.sequencia_numeracao:
-            numeracao = tipo.sequencia_numeracao
-
         if numeracao == 'A':
-            numero = MateriaLegislativa.objects.filter(
+            numero = Protocolo.objects.filter(
                 ano=timezone.now().year, tipo=tipo).aggregate(Max('numero'))
         elif numeracao == 'L':
             legislatura = Legislatura.objects.filter(
@@ -443,13 +434,12 @@ def form_valid(self, form):
                 data_fim__year__gte=timezone.now().year).first()
             data_inicio = legislatura.data_inicio
             data_fim = legislatura.data_fim
-            numero = MateriaLegislativa.objects.filter(
-                data_apresentacao__gte=data_inicio,
-                data_apresentacao__lte=data_fim,
-                tipo=tipo).aggregate(
+            numero = Protocolo.objects.filter(
+                data__gte=data_inicio,
+                data__lte=data_fim).aggregate(
                 Max('numero'))
         elif numeracao == 'U':
-            numero = MateriaLegislativa.objects.filter(tipo=tipo).aggregate(Max('numero'))
+            numero = Protocolo.objects.filter().aggregate(Max('numero'))
 
         if numeracao is None:
             numero['numero__max'] = 0


Test patch: