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
@@ -412,6 +412,8 @@ def clean(self):
         if self.is_valid():
             if data['vincular_materia'] == 'True':
                 try:
+                    if not data['ano_materia'] or not data['numero_materia']:
+                            raise ValidationError('Favor informar o número e ano da matéria a ser vinculada')
                     self.materia = MateriaLegislativa.objects.get(ano=data['ano_materia'],
                                                                   numero=data['numero_materia'],
                                                                   tipo=data['tipo_materia'])
diff --git a/sapl/protocoloadm/views.py b/sapl/protocoloadm/views.py
--- a/sapl/protocoloadm/views.py
+++ b/sapl/protocoloadm/views.py
@@ -277,8 +277,7 @@ def get_success_url(self):
                        kwargs={'pk': self.object.id})
 
     def form_valid(self, form):
-        f = form.save(commit=False)
-
+        protocolo = form.save(commit=False)
         try:
             numeracao = sapl.base.models.AppConfig.objects.last(
             ).sequencia_numeracao
@@ -288,30 +287,36 @@ 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 = Protocolo.objects.filter(
-                ano=timezone.now().year).aggregate(Max('numero'))
+            numero = DocumentoAdministrativo.objects.filter(
+                ano=timezone.now().year, tipo=tipo).aggregate(Max('numero'))
         elif numeracao == 'L':
-            legislatura = Legislatura.objects.first()
+            legislatura = Legislatura.objects.filter(
+                data_inicio__year__lte=timezone.now().year,
+                data_fim__year__gte=timezone.now().year).first()
             data_inicio = legislatura.data_inicio
             data_fim = legislatura.data_fim
-            numero = Protocolo.objects.filter(
-                data__gte=data_inicio, data__lte=data_fim).aggregate(
-                    Max('numero'))
+            numero = DocumentoAdministrativo.objects.filter(
+                data__gte=data_inicio,
+                data__lte=data_fim,
+                tipo=tipo).aggregate(
+                Max('numero'))
         elif numeracao == 'U':
-            numero = Protocolo.objects.all().aggregate(Max('numero'))
-
-        f.tipo_processo = '0'  # TODO validar o significado
-        f.anulado = False
-        f.numero = (numero['numero__max'] + 1) if numero['numero__max'] else 1
-        f.ano = timezone.now().year
-        f.data = timezone.now()
-        f.hora = timezone.now().time()
-        f.timestamp = timezone.now()
-        f.assunto_ementa = self.request.POST['assunto']
-
-        f.save()
-        self.object = f
+            numero = DocumentoAdministrativo.objects.filter(tipo=tipo).aggregate(Max('numero'))
+
+        protocolo.tipo_processo = '0'  # TODO validar o significado
+        protocolo.anulado = False
+        protocolo.numero = (numero['numero__max'] + 1) if numero['numero__max'] else 1
+        protocolo.ano = timezone.now().year
+        protocolo.data = timezone.now()
+        protocolo.hora = timezone.now().time()
+        protocolo.timestamp = timezone.now()
+        protocolo.assunto_ementa = self.request.POST['assunto']
+
+        protocolo.save()
+        self.object = protocolo
         return redirect(self.get_success_url())
 
 
@@ -414,7 +419,6 @@ def get_success_url(self, protocolo):
             'pk': protocolo.pk})
 
     def form_valid(self, form):
-
         try:
             numeracao = sapl.base.models.AppConfig.objects.last(
             ).sequencia_numeracao
@@ -431,17 +435,21 @@ def form_valid(self, form):
             numeracao = tipo.sequencia_numeracao
 
         if numeracao == 'A':
-            numero = Protocolo.objects.filter(
-                ano=timezone.now().year).aggregate(Max('numero'))
+            numero = MateriaLegislativa.objects.filter(
+                ano=timezone.now().year, tipo=tipo).aggregate(Max('numero'))
         elif numeracao == 'L':
-            legislatura = Legislatura.objects.first()
+            legislatura = Legislatura.objects.filter(
+                data_inicio__year__lte=timezone.now().year,
+                data_fim__year__gte=timezone.now().year).first()
             data_inicio = legislatura.data_inicio
             data_fim = legislatura.data_fim
-            numero = Protocolo.objects.filter(
-                data__gte=data_inicio, data__lte=data_fim).aggregate(
-                    Max('numero'))
+            numero = MateriaLegislativa.objects.filter(
+                data_apresentacao__gte=data_inicio,
+                data_apresentacao__lte=data_fim,
+                tipo=tipo).aggregate(
+                Max('numero'))
         elif numeracao == 'U':
-            numero = Protocolo.objects.all().aggregate(Max('numero'))
+            numero = MateriaLegislativa.objects.filter(tipo=tipo).aggregate(Max('numero'))
 
         if numeracao is None:
             numero['numero__max'] = 0
@@ -469,11 +477,12 @@ def form_valid(self, form):
 
         protocolo.save()
         data = form.cleaned_data
-        materia = MateriaLegislativa.objects.get(ano=data['ano_materia'],
-                                                 numero=data['numero_materia'],
-                                                 tipo=data['tipo_materia'])
-        materia.numero_protocolo = protocolo.numero
-        materia.save()
+        if data['vincular_materia'] == 'True':
+            materia = MateriaLegislativa.objects.get(ano=data['ano_materia'],
+                                                     numero=data['numero_materia'],
+                                                     tipo=data['tipo_materia'])
+            materia.numero_protocolo = protocolo.numero
+            materia.save()
 
         return redirect(self.get_success_url(protocolo))
 


Test patch: