Browse Source

Refatoração de AnularProtocolo e bug fix de Cadastrar Protocolo

pull/250/head
Edward Ribeiro 9 years ago
parent
commit
b902cf753b
  1. 79
      protocoloadm/forms.py
  2. 156
      protocoloadm/views.py
  3. 9
      sapl/utils.py

79
protocoloadm/forms.py

@ -3,6 +3,7 @@ from datetime import date
from crispy_forms.helper import FormHelper from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Field, Fieldset, Layout, Submit from crispy_forms.layout import HTML, Field, Fieldset, Layout, Submit
from django import forms from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ModelForm from django.forms import ModelForm
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -12,8 +13,8 @@ from crispy_layout_mixin import form_actions
from materia.models import TipoMateriaLegislativa from materia.models import TipoMateriaLegislativa
from .models import (Autor, DocumentoAcessorioAdministrativo, from .models import (Autor, DocumentoAcessorioAdministrativo,
DocumentoAdministrativo, TipoDocumentoAdministrativo, DocumentoAdministrativo, Protocolo,
TramitacaoAdministrativo) TipoDocumentoAdministrativo, TramitacaoAdministrativo)
def get_range_anos(): def get_range_anos():
@ -132,25 +133,54 @@ class ProtocoloForm(forms.Form):
*args, **kwargs) *args, **kwargs)
class AnularProcoloAdmForm(forms.Form): class AnularProcoloAdmForm(ModelForm):
YEARS = get_range_anos() YEARS = get_range_anos()
numero_protocolo = forms.CharField( numero = forms.CharField(
label=_('Número de Protocolo'), required=True) label=_('Número de Protocolo'), required=True)
ano_protocolo = forms.ChoiceField(required=False, ano = forms.ChoiceField(required=False,
label='Ano', label='Ano',
choices=YEARS, choices=YEARS,
widget=forms.Select( widget=forms.Select(attrs={'class': 'selector'}))
attrs={'class': 'selector'}))
justificativa_anulacao = forms.CharField( justificativa_anulacao = forms.CharField(
widget=forms.Textarea, label='Motivo', required=True) widget=forms.Textarea, label='Motivo', required=True)
def clean(self):
cleaned_data = super(AnularProcoloAdmForm, self).clean()
numero = cleaned_data.get("numero")
ano = cleaned_data.get("ano")
try:
protocolo = Protocolo.objects.get(numero=numero, ano=ano)
if protocolo.anulado:
raise forms.ValidationError(
_("Protocolo %s/%s já encontra-se anulado")
% (numero, ano))
except ObjectDoesNotExist:
raise forms.ValidationError(
_("Protocolo %s/%s não existe" % (numero, ano)))
class Meta:
model = Protocolo
fields = ['numero',
'ano',
'justificativa_anulacao',
'anulado',
'user_anulacao',
'ip_anulacao',
]
widgets = {'anulado': forms.HiddenInput(),
'user_anulacao': forms.HiddenInput(),
'ip_anulacao': forms.HiddenInput(),
}
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
row1 = crispy_layout_mixin.to_row( row1 = crispy_layout_mixin.to_row(
[('numero_protocolo', 6), [('numero', 6),
('ano_protocolo', 6)]) ('ano', 6)])
row2 = crispy_layout_mixin.to_row( row2 = crispy_layout_mixin.to_row(
[('justificativa_anulacao', 12)]) [('justificativa_anulacao', 12)])
@ -167,7 +197,7 @@ class AnularProcoloAdmForm(forms.Form):
*args, **kwargs) *args, **kwargs)
class ProtocoloDocumentForm(forms.Form): class ProtocoloDocumentForm(ModelForm):
NUMERACAO_CHOICES = [('1', _('Sequencial por Ano')), NUMERACAO_CHOICES = [('1', _('Sequencial por Ano')),
('2', _('Sequencial Único'))] ('2', _('Sequencial Único'))]
@ -201,6 +231,17 @@ class ProtocoloDocumentForm(forms.Form):
observacao = forms.CharField(required=True, observacao = forms.CharField(required=True,
widget=forms.Textarea, label='Observação') widget=forms.Textarea, label='Observação')
class Meta:
model = Protocolo
fields = ['numeracao',
'tipo_protocolo',
'tipo_documento',
'num_paginas',
'assunto',
'interessado',
'observacao',
]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
row1 = crispy_layout_mixin.to_row( row1 = crispy_layout_mixin.to_row(
@ -234,7 +275,7 @@ class ProtocoloDocumentForm(forms.Form):
*args, **kwargs) *args, **kwargs)
class ProtocoloMateriaForm(forms.Form): class ProtocoloMateriaForm(ModelForm):
NUMERACAO_CHOICES = [('1', _('Sequencial por Ano')), NUMERACAO_CHOICES = [('1', _('Sequencial por Ano')),
('2', _('Sequencial Único'))] ('2', _('Sequencial Único'))]
@ -273,6 +314,17 @@ class ProtocoloMateriaForm(forms.Form):
widget=forms.Textarea, widget=forms.Textarea,
label='Observação') label='Observação')
class Meta:
model = Protocolo
fields = ['numeracao',
'tipo_protocolo',
'tipo_materia',
'num_paginas',
'ementa',
'autor',
'observacao',
]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
row1 = crispy_layout_mixin.to_row( row1 = crispy_layout_mixin.to_row(
@ -299,6 +351,7 @@ class ProtocoloMateriaForm(forms.Form):
form_actions(save_label=_('Protocolar Matéria')) form_actions(save_label=_('Protocolar Matéria'))
) )
) )
super(ProtocoloMateriaForm, self).__init__( super(ProtocoloMateriaForm, self).__init__(
*args, **kwargs) *args, **kwargs)

156
protocoloadm/views.py

@ -2,8 +2,6 @@ from datetime import date, datetime
from re import sub from re import sub
from braces.views import FormValidMessageMixin from braces.views import FormValidMessageMixin
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse, reverse_lazy from django.core.urlresolvers import reverse, reverse_lazy
from django.db.models import Max from django.db.models import Max
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
@ -17,7 +15,7 @@ from vanilla import GenericView
from crud import Crud, make_pagination from crud import Crud, make_pagination
from materia.models import Proposicao, TipoMateriaLegislativa from materia.models import Proposicao, TipoMateriaLegislativa
from sapl.utils import create_barcode from sapl.utils import create_barcode, get_client_ip
from .forms import (AnularProcoloAdmForm, DocumentoAcessorioAdministrativoForm, from .forms import (AnularProcoloAdmForm, DocumentoAcessorioAdministrativoForm,
DocumentoAdministrativoForm, ProposicaoSimpleForm, DocumentoAdministrativoForm, ProposicaoSimpleForm,
@ -47,13 +45,6 @@ class ProtocoloPesquisaView(FormView):
context_object_name = 'protocolos' context_object_name = 'protocolos'
success_url = reverse_lazy('protocolo') success_url = reverse_lazy('protocolo')
extra_context = {}
def get_context_data(self, **kwargs):
context = super(ProtocoloPesquisaView, self).get_context_data(**kwargs)
context.update(self.extra_context)
return context
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
form = ProtocoloForm(request.POST or None) form = ProtocoloForm(request.POST or None)
@ -124,74 +115,47 @@ class ProtocoloListView(ListView):
return context return context
def get_client_ip(request): class AnularProtocoloAdmView(FormView):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
class AnularProtocoloAdmView(FormValidMessageMixin, FormView):
template_name = 'protocoloadm/anular_protocoloadm.html' template_name = 'protocoloadm/anular_protocoloadm.html'
form_class = AnularProcoloAdmForm form_class = AnularProcoloAdmForm
success_url = reverse_lazy('anular_protocolo') success_url = reverse_lazy('anular_protocolo')
form_valid_message = _('Protocolo anulado com sucesso!') form_valid_message = _('Protocolo anulado com sucesso!')
def get_initial(self):
initial_data = {}
initial_data['user_anulacao'] = self.request.user.username
initial_data['ip_anulacao'] = get_client_ip(self.request)
initial_data['anulado'] = True
return initial_data
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
form = AnularProcoloAdmForm(request.POST) form = AnularProcoloAdmForm(request.POST)
if form.is_valid(): if form.is_valid():
numero = request.POST['numero_protocolo'] numero = form.cleaned_data['numero']
ano = request.POST['ano_protocolo'] ano = form.cleaned_data['ano']
justificativa_anulacao = sub(' ', ' ', strip_tags(
request.POST['justificativa_anulacao'])) protocolo = Protocolo.objects.get(numero=numero, ano=ano)
protocolo.anulado = True
user_anulacao = request.user.username protocolo.justificativa_anulacao = sub(' ', ' ', strip_tags(
ip_addr = get_client_ip(request) form.cleaned_data['justificativa_anulacao']))
protocolo.user_anulacao = form.cleaned_data['user_anulacao']
try: protocolo.ip_anulacao = form.cleaned_data['ip_anulacao']
protocolo = Protocolo.objects.get(numero=numero, ano=ano) protocolo.save()
if protocolo.anulado:
errors = form._errors.setdefault(
forms.forms.NON_FIELD_ERRORS,
forms.util.ErrorList())
errors.append(_("Protocolo %s/%s já encontra-se anulado")
% (numero, ano))
return self.form_invalid(form)
protocolo.anulado = True
protocolo.justificativa_anulacao = justificativa_anulacao
protocolo.user_anulacao = user_anulacao
protocolo.ip_anulacao = ip_addr
protocolo.save()
return self.form_valid(form)
except ObjectDoesNotExist: return self.form_valid(form)
errors = form._errors.setdefault(
forms.forms.NON_FIELD_ERRORS, forms.util.ErrorList())
errors.append(_("Protocolo %s/%s não existe" % (numero, ano)))
return self.form_invalid(form)
else: else:
return self.form_invalid(form) return self.form_invalid(form)
class ProtocoloDocumentoView(FormMixin, GenericView): class ProtocoloDocumentoView(FormValidMessageMixin, CreateView):
template_name = "protocoloadm/protocolar_documento.html" template_name = "protocoloadm/protocolar_documento.html"
model = Protocolo
form_class = ProtocoloDocumentForm form_class = ProtocoloDocumentForm
success_url = reverse_lazy('protocolo')
def get_success_url(self): form_valid_message = _('Protocolo cadastrado com sucesso!')
return reverse('protocolo')
def get(self, request, *args, **kwargs):
form = ProtocoloDocumentForm()
return self.render_to_response({'form': form})
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
@ -207,7 +171,7 @@ class ProtocoloDocumentoView(FormMixin, GenericView):
if numeracao['numero__max'] is None: if numeracao['numero__max'] is None:
numeracao['numero__max'] = 0 numeracao['numero__max'] = 0
protocolo = Protocolo() protocolo = form.save(commit=False)
protocolo.numero = numeracao['numero__max'] + 1 protocolo.numero = numeracao['numero__max'] + 1
protocolo.ano = datetime.now().year protocolo.ano = datetime.now().year
protocolo.data = datetime.now().strftime("%Y-%m-%d") protocolo.data = datetime.now().strftime("%Y-%m-%d")
@ -224,32 +188,14 @@ class ProtocoloDocumentoView(FormMixin, GenericView):
protocolo.numero_paginas = request.POST['num_paginas'] protocolo.numero_paginas = request.POST['num_paginas']
protocolo.observacao = sub( protocolo.observacao = sub(
' ', ' ', strip_tags(request.POST['observacao'])) ' ', ' ', strip_tags(request.POST['observacao']))
protocolo.save()
return self.form_valid(form) return self.form_valid(form)
else: else:
return self.form_invalid(form) return self.form_invalid(form)
def criar_documento(protocolo):
doc = {}
numero = Protocolo.objects.filter(
tipo_documento=protocolo.tipo_documento,
ano=protocolo.ano,
anulado=False).aggregate(Max('numero'))
doc['tipo'] = protocolo.tipo_documento
doc['ano'] = protocolo.ano
doc['data'] = protocolo.data
doc['numero_protocolo'] = protocolo.numero
doc['assunto'] = protocolo.assunto_ementa
doc['interessado'] = protocolo.interessado
doc['numero'] = numero['numero__max']
if doc['numero'] is None:
doc['numero'] = 1
return doc
class CriarDocumentoProtocolo(CreateView): class CriarDocumentoProtocolo(CreateView):
template_name = "protocoloadm/criar_documento.html" template_name = "protocoloadm/criar_documento.html"
form_class = DocumentoAdministrativoForm form_class = DocumentoAdministrativoForm
@ -258,29 +204,52 @@ class CriarDocumentoProtocolo(CreateView):
numero = self.kwargs['pk'] numero = self.kwargs['pk']
ano = self.kwargs['ano'] ano = self.kwargs['ano']
protocolo = Protocolo.objects.get(ano=ano, numero=numero) protocolo = Protocolo.objects.get(ano=ano, numero=numero)
return criar_documento(protocolo) return self.criar_documento(protocolo)
def get_success_url(self): def get_success_url(self):
return reverse('protocolo_mostrar', kwargs={'pk': self.kwargs['pk'], return reverse('protocolo_mostrar', kwargs={'pk': self.kwargs['pk'],
'ano': self.kwargs['ano']}) 'ano': self.kwargs['ano']})
def criar_documento(self, protocolo):
numero = Protocolo.objects.filter(
tipo_documento=protocolo.tipo_documento,
ano=protocolo.ano,
anulado=False).aggregate(Max('numero'))
doc = {}
doc['tipo'] = protocolo.tipo_documento
doc['ano'] = protocolo.ano
doc['data'] = protocolo.data
doc['numero_protocolo'] = protocolo.numero
doc['assunto'] = protocolo.assunto_ementa
doc['interessado'] = protocolo.interessado
doc['numero'] = numero['numero__max']
if doc['numero'] is None:
doc['numero'] = 1
return doc
class ProtocoloMostrarView(TemplateView): class ProtocoloMostrarView(TemplateView):
template_name = "protocoloadm/protocolo_mostrar.html" template_name = "protocoloadm/protocolo_mostrar.html"
def get(self, request, *args, **kwargs): def get_context_data(self, **kwargs):
context = super(ProtocoloMostrarView, self).get_context_data(**kwargs)
numero = self.kwargs['pk'] numero = self.kwargs['pk']
ano = self.kwargs['ano'] ano = self.kwargs['ano']
protocolo = Protocolo.objects.get(ano=ano, numero=numero) protocolo = Protocolo.objects.get(ano=ano, numero=numero)
return self.render_to_response({"protocolo": protocolo}) context['protocolo'] = protocolo
return context
class ComprovanteProtocoloView(TemplateView): class ComprovanteProtocoloView(TemplateView):
template_name = "protocoloadm/comprovante.html" template_name = "protocoloadm/comprovante.html"
def get(self, request, *args, **kwargs): def get_context_data(self, **kwargs):
context = super(ComprovanteProtocoloView, self).get_context_data(
**kwargs)
numero = self.kwargs['pk'] numero = self.kwargs['pk']
ano = self.kwargs['ano'] ano = self.kwargs['ano']
protocolo = Protocolo.objects.get(ano=ano, numero=numero) protocolo = Protocolo.objects.get(ano=ano, numero=numero)
@ -295,20 +264,21 @@ class ComprovanteProtocoloView(TemplateView):
protocolo.data.strftime("%Y/%m/%d") + \ protocolo.data.strftime("%Y/%m/%d") + \
str(protocolo.numero).zfill(6) str(protocolo.numero).zfill(6)
return self.render_to_response({"protocolo": protocolo, context.update({"protocolo": protocolo,
"barcode": barcode, "barcode": barcode,
"autenticacao": autenticacao}) "autenticacao": autenticacao})
return context
class ProtocoloMateriaView(FormMixin, GenericView): class ProtocoloMateriaView(FormValidMessageMixin, CreateView):
template_name = "protocoloadm/protocolar_materia.html" template_name = "protocoloadm/protocolar_materia.html"
model = Protocolo
form_class = ProtocoloMateriaForm form_class = ProtocoloMateriaForm
form_valid_message = _('Matéria cadastrada com sucesso!')
def get(self, request, *args, **kwargs): def get_initial(self):
form = ProtocoloMateriaForm() initial = {}
return self.render_to_response({'form': form}) return initial
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):

9
sapl/utils.py

@ -21,6 +21,15 @@ def xstr(s):
return '' if s is None else str(s) return '' if s is None else str(s)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def get_base_url(request): def get_base_url(request):
# TODO substituir por Site.objects.get_current().domain # TODO substituir por Site.objects.get_current().domain
# from django.contrib.sites.models import Site # from django.contrib.sites.models import Site

Loading…
Cancel
Save