Browse Source

Merge pull request #339 from interlegis/327-refatora-pesquisa-protocolo

fix #327 refatora pesquisa protocolo
pull/346/head
Edward 9 years ago
parent
commit
edb577d7d4
  1. 137
      protocoloadm/forms.py
  2. 89
      protocoloadm/views.py
  3. 70
      templates/protocoloadm/protocolo_filter.html

137
protocoloadm/forms.py

@ -1,110 +1,112 @@
from datetime import date import django_filters
from crispy_forms.bootstrap import InlineRadios from crispy_forms.bootstrap import InlineRadios
from crispy_forms.helper import FormHelper from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Button, Field, Fieldset, Layout, Submit from crispy_forms.layout import HTML, Button, Field, Fieldset, Layout, Submit
from django import forms from django import forms
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.forms import ModelForm from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
import crispy_layout_mixin import crispy_layout_mixin
import sapl import sapl
from crispy_layout_mixin import form_actions from crispy_layout_mixin import form_actions
from materia.models import Autor, TipoMateriaLegislativa from materia.forms import RangeWidgetOverride
from materia.models import Autor
from sapl.utils import RANGE_ANOS from sapl.utils import RANGE_ANOS
from .models import (DocumentoAcessorioAdministrativo, DocumentoAdministrativo, from .models import (DocumentoAcessorioAdministrativo, DocumentoAdministrativo,
Protocolo, TipoDocumentoAdministrativo, Protocolo, TipoDocumentoAdministrativo,
TramitacaoAdministrativo) TramitacaoAdministrativo)
TIPOS_PROTOCOLO = [('0', 'Enviado'), ('1', 'Recebido')] TIPOS_PROTOCOLO = [('0', 'Enviado'), ('1', 'Recebido'), ('', 'Ambos')]
NATUREZA_PROCESSO = [('0', 'Administrativo'), NATUREZA_PROCESSO = [('0', 'Administrativo'),
('1', 'Legislativo'), ('1', 'Legislativo'),
('', 'Ambos')] ('', 'Ambos')]
def get_range_anos(): ANO_CHOICES = [('', '---------')] + RANGE_ANOS
return [('', 'Selecione')] \
+ [(year, year) for year in range(date.today().year, 1960, -1)]
class ProtocoloForm(forms.Form): class ProtocoloFilterSet(django_filters.FilterSet):
YEARS = get_range_anos() filter_overrides = {models.DateField: {
'filter_class': django_filters.DateFromToRangeFilter,
'extra': lambda f: {
'label': 'Data (%s)' % (_('Inicial - Final')),
'widget': RangeWidgetOverride}
}}
tipo_protocolo = forms.ChoiceField(required=False, ano = django_filters.ChoiceFilter(required=False,
label='Tipo de Protocolo', label=u'Ano da Matéria',
choices=TIPOS_PROTOCOLO, choices=ANO_CHOICES)
widget=forms.Select(
attrs={'class': 'selector'}))
numero_protocolo = forms.CharField( assunto_ementa = django_filters.CharFilter(lookup_expr='icontains')
label='Número de Protocolo', required=False)
ano = forms.ChoiceField(required=False, interessado = django_filters.CharFilter(lookup_expr='icontains')
label='Ano',
choices=YEARS,
widget=forms.Select(
attrs={'class': 'selector'}))
inicial = forms.DateField(label='Data Inicial', autor = django_filters.CharFilter(widget=forms.HiddenInput())
required=False,
widget=forms.TextInput(
attrs={'class': 'dateinput'}))
final = forms.DateField(label='Data Final', required=False,
widget=forms.TextInput(
attrs={'class': 'dateinput'}))
natureza_processo = forms.ChoiceField(required=False,
label='Natureza Processo',
choices=[
('0', 'Administrativo'),
('1', 'Legislativo'),
('', 'Ambos')])
tipo_documento = forms.ModelChoiceField( tipo_protocolo = django_filters.ChoiceFilter(required=False,
label='Tipo de Documento', label='Tipo de Protocolo',
required=False, choices=TIPOS_PROTOCOLO,
queryset=TipoDocumentoAdministrativo.objects.all(), widget=forms.Select(
empty_label='Selecione', attrs={'class': 'selector'}))
)
interessado = forms.CharField(label='Interessado', required=False) class Meta:
model = Protocolo
fields = ['numero',
'tipo_documento',
'data',
'tipo_materia',
]
tipo_materia = forms.ModelChoiceField( order_by = (
label='Tipo de Matéria', ('', 'Selecione'),
required=False, ('CRE', 'Ordem Crescente'),
queryset=TipoMateriaLegislativa.objects.all(), ('DEC', 'Ordem Decrescente'),
empty_label='Selecione',
) )
autor = forms.CharField(widget=forms.HiddenInput(), required=False) order_by_mapping = {
'': [],
'CRE': ['ano', 'numero'],
'DEC': ['-ano', '-numero'],
}
assunto = forms.CharField(label='Assunto', required=False) def get_order_by(self, order_value):
if order_value in self.order_by_mapping:
return self.order_by_mapping[order_value]
else:
return super(ProtocoloFilterSet,
self).get_order_by(order_value)
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(ProtocoloFilterSet, self).__init__(*args, **kwargs)
self.filters['autor'].label = 'Tipo de Matéria'
self.filters['assunto_ementa'].label = 'Assunto'
row1 = crispy_layout_mixin.to_row( row1 = crispy_layout_mixin.to_row(
[('numero_protocolo', 6), [('numero', 4),
('ano', 6)]) ('ano', 4),
('data', 4)])
row2 = crispy_layout_mixin.to_row( row2 = crispy_layout_mixin.to_row(
[('inicial', 6), [('tipo_documento', 4),
('final', 6)]) ('tipo_protocolo', 4),
('tipo_materia', 4)])
row3 = crispy_layout_mixin.to_row( row3 = crispy_layout_mixin.to_row(
[('tipo_documento', 4), [('tipo_documento', 4),
('tipo_protocolo', 4), ('tipo_protocolo', 4),
('tipo_materia', 4)]) ('tipo_materia', 4)])
row4 = crispy_layout_mixin.to_row( row3 = crispy_layout_mixin.to_row(
[('interessado', 6), [('interessado', 6),
('assunto', 6)]) ('assunto_ementa', 6)])
row5 = crispy_layout_mixin.to_row( row4 = crispy_layout_mixin.to_row(
[('autor', 0), [('autor', 0),
(Button('pesquisar', (Button('pesquisar',
'Pesquisar Autor', 'Pesquisar Autor',
@ -112,21 +114,20 @@ class ProtocoloForm(forms.Form):
(Button('limpar', (Button('limpar',
'Limpar Autor', 'Limpar Autor',
css_class='btn btn-primary btn-sm'), 10)]) css_class='btn btn-primary btn-sm'), 10)])
row5 = crispy_layout_mixin.to_row(
[('o', 12)])
row6 = crispy_layout_mixin.to_row( self.form.helper = FormHelper()
[('natureza_processo', 12)]) self.form.helper.form_method = 'GET'
self.form.helper.layout = Layout(
self.helper = FormHelper() Fieldset(_('Pesquisar Protocolo'),
self.helper.layout = Layout(Fieldset(_('Pesquisar Protocolo'),
row1, row2, row1, row2,
row3, row4, row3,
HTML(sapl.utils.autor_label), HTML(sapl.utils.autor_label),
HTML(sapl.utils.autor_modal), HTML(sapl.utils.autor_modal),
row5, row4, row5,
row6, form_actions(save_label='Pesquisar'))
form_actions(save_label='Pesquisar'))) )
super(ProtocoloForm, self).__init__(
*args, **kwargs)
class AnularProcoloAdmForm(ModelForm): class AnularProcoloAdmForm(ModelForm):

89
protocoloadm/views.py

@ -2,13 +2,14 @@ import json
from datetime import date, datetime from datetime import date, datetime
from braces.views import FormValidMessageMixin from braces.views import FormValidMessageMixin
from django.core.urlresolvers import reverse, reverse_lazy from django.core.urlresolvers import reverse
from django.db.models import Q, Max from django.db.models import Q, Max
from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, DetailView, FormView, ListView from django.views.generic import CreateView, DetailView, FormView, ListView
from django.views.generic.base import TemplateView from django.views.generic.base import TemplateView
from django_filters.views import FilterView
from crud.base import Crud, make_pagination from crud.base import Crud, make_pagination
from materia.models import Proposicao, TipoMateriaLegislativa from materia.models import Proposicao, TipoMateriaLegislativa
@ -16,8 +17,8 @@ from sapl.utils import create_barcode, get_client_ip
from .forms import (AnularProcoloAdmForm, DocumentoAcessorioAdministrativoForm, from .forms import (AnularProcoloAdmForm, DocumentoAcessorioAdministrativoForm,
DocumentoAdministrativoForm, ProposicaoSimpleForm, DocumentoAdministrativoForm, ProposicaoSimpleForm,
ProtocoloDocumentForm, ProtocoloForm, ProtocoloMateriaForm, ProtocoloDocumentForm, ProtocoloFilterSet,
TramitacaoAdmForm) ProtocoloMateriaForm, TramitacaoAdmForm)
from .models import (Autor, DocumentoAcessorioAdministrativo, from .models import (Autor, DocumentoAcessorioAdministrativo,
DocumentoAdministrativo, Protocolo, DocumentoAdministrativo, Protocolo,
StatusTramitacaoAdministrativo, StatusTramitacaoAdministrativo,
@ -37,57 +38,63 @@ ProtocoloDocumentoCrud = Crud.build(Protocolo, '')
ProtocoloMateriaCrud = Crud.build(Protocolo, '') ProtocoloMateriaCrud = Crud.build(Protocolo, '')
class ProtocoloPesquisaView(FormView): class ProtocoloPesquisaView(FilterView):
template_name = 'protocoloadm/protocolo_pesquisa.html' model = Protocolo
form_class = ProtocoloForm filterset_class = ProtocoloFilterSet
context_object_name = 'protocolos' paginate_by = 10
success_url = reverse_lazy('protocoloadm:protocolo')
def post(self, request, *args, **kwargs):
form = ProtocoloForm(request.POST or None)
if form.is_valid(): def get_filterset_kwargs(self, filterset_class):
kwargs = {} super(ProtocoloPesquisaView,
self).get_filterset_kwargs(filterset_class)
if request.POST['tipo_protocolo']: kwargs = {'data': self.request.GET or None}
kwargs['tipo_protocolo'] = request.POST['tipo_protocolo']
if request.POST['numero_protocolo']: qs = self.get_queryset()
kwargs['numero'] = request.POST['numero_protocolo']
if request.POST['ano']: qs = qs.distinct()
kwargs['ano'] = request.POST['ano']
if request.POST['inicial']: kwargs.update({
kwargs['data'] = datetime.strptime( 'queryset': qs,
request.POST['inicial'], })
'%d/%m/%Y').strftime('%Y-%m-%d') return kwargs
# if request.POST['final']: def get_context_data(self, **kwargs):
# kwargs['final'] = request.POST['final'] context = super(ProtocoloPesquisaView,
self).get_context_data(**kwargs)
# if request.POST['natureza_processo']: paginator = context['paginator']
# kwargs['natureza_processo'] = request.POST['natureza_processo'] page_obj = context['page_obj']
if request.POST['tipo_documento']: context['page_range'] = make_pagination(
kwargs['tipo_documento'] = request.POST['tipo_documento'] page_obj.number, paginator.num_pages)
if request.POST['interessado']: return context
kwargs['interessado__icontains'] = request.POST['interessado']
if request.POST['tipo_materia']: def get(self, request, *args, **kwargs):
kwargs['tipo_materia'] = request.POST['tipo_materia'] super(ProtocoloPesquisaView, self).get(request)
# Se a pesquisa estiver quebrando com a paginação
# Olhe esta função abaixo
# Provavelmente você criou um novo campo no Form/FilterSet
# Então a ordem da URL está diferente
data = self.filterset.data
if (data and data.get('numero') is not None):
url = "&"+str(self.request.environ['QUERY_STRING'])
if url.startswith("&page"):
ponto_comeco = url.find('numero=') - 1
url = url[ponto_comeco:]
else:
url = ''
if request.POST['autor']: self.filterset.form.fields['o'].label = _('Ordenação')
kwargs['autor'] = request.POST['autor']
if request.POST['assunto']: context = self.get_context_data(filter=self.filterset,
kwargs['assunto_ementa__icontains'] = request.POST['assunto'] object_list=self.object_list,
filter_url=url,
numero_res=len(self.object_list)
)
request.session['kwargs'] = kwargs return self.render_to_response(context)
return redirect('protocoloadm:protocolo_list')
else:
return self.form_invalid(form)
class ProtocoloListView(ListView): class ProtocoloListView(ListView):

70
templates/protocoloadm/protocolo_filter.html

@ -0,0 +1,70 @@
{% extends "protocoloadm/protocoloadm_detail.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% load static %}
{% block actions %}{% endblock %}
{% block sections_nav %} {% endblock %}
{% block detail_content %}
<h1><b>Pesquisar Protocolo</b></h1>
<br></br>
{% crispy filter.form %}
<p></p>
<table class="table table-striped table-bordered">
<thead class="thead-default">
<tr><td><h3>Resultados</h3></td></tr>
</thead>
{% if page_obj|length %}
{% if filter_url %}
{% if numero_res > 1 %}
<h3>Pesquisa concluída com sucesso! Foram encontrados {{numero_res}} protocolos.</h3>
{% elif numero_res == 1 %}
<h3>Pesquisa concluída com sucesso! Foi encontrado {{numero_res}} protocolo.</h3>
{% endif %}
{% endif %}
{% for p in page_obj %}
<tr>
<td>
<strong>Protocolo:
<a href="{% url 'protocoloadm:protocolo_mostrar' p.numero p.ano %}">
{{ p.numero|stringformat:'06d' }}/{{ p.ano }}
</a></strong>
&nbsp;&nbsp;<strong>-</strong>&nbsp;&nbsp;
<a href="{% url 'relatorios:relatorio_etiqueta_protocolo' p.numero p.ano %}">
<img src="{% static 'img/etiqueta.png' %}" alt="Etiqueta Individual">
</a></br>
<strong>Assunto:</strong> {{ p.assunto_ementa|default_if_none:"Não Informado"}}</br>
<strong>Data Protocolo:</strong> {{ p.data|date:"d/m/Y"|default_if_none:"Não Informado" }} - Horário: {{ p.timestamp|date:"H:m:s" }}</br>
<strong>Interessado:</strong> {{ p.interessado }}</br>
<strong>Natureza do Processo:</strong>
{% if p.tipo_processo == 0 %}
Administrativo
{% elif p.tipo_processo == 1 %}
Matéria Legislativa
{% endif %}</br>
<strong>Classificação:</strong> {{ p.tipo_documento|default_if_none:"Não Informado" }} </br>
<p></p>
</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td>
<h3>Nenhum protocolo encontrado com essas especificações</h3>
</tr>
{% endif %}
</table>
{% include "paginacao.html" %}
{% endblock detail_content %}
Loading…
Cancel
Save