Browse Source

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

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

75
protocoloadm/forms.py

@ -3,6 +3,7 @@ from datetime import date
from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Field, Fieldset, Layout, Submit
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ModelForm
from django.utils.safestring import mark_safe
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 .models import (Autor, DocumentoAcessorioAdministrativo,
DocumentoAdministrativo, TipoDocumentoAdministrativo,
TramitacaoAdministrativo)
DocumentoAdministrativo, Protocolo,
TipoDocumentoAdministrativo, TramitacaoAdministrativo)
def get_range_anos():
@ -132,25 +133,54 @@ class ProtocoloForm(forms.Form):
*args, **kwargs)
class AnularProcoloAdmForm(forms.Form):
class AnularProcoloAdmForm(ModelForm):
YEARS = get_range_anos()
numero_protocolo = forms.CharField(
numero = forms.CharField(
label=_('Número de Protocolo'), required=True)
ano_protocolo = forms.ChoiceField(required=False,
ano = forms.ChoiceField(required=False,
label='Ano',
choices=YEARS,
widget=forms.Select(
attrs={'class': 'selector'}))
widget=forms.Select(attrs={'class': 'selector'}))
justificativa_anulacao = forms.CharField(
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):
row1 = crispy_layout_mixin.to_row(
[('numero_protocolo', 6),
('ano_protocolo', 6)])
[('numero', 6),
('ano', 6)])
row2 = crispy_layout_mixin.to_row(
[('justificativa_anulacao', 12)])
@ -167,7 +197,7 @@ class AnularProcoloAdmForm(forms.Form):
*args, **kwargs)
class ProtocoloDocumentForm(forms.Form):
class ProtocoloDocumentForm(ModelForm):
NUMERACAO_CHOICES = [('1', _('Sequencial por Ano')),
('2', _('Sequencial Único'))]
@ -201,6 +231,17 @@ class ProtocoloDocumentForm(forms.Form):
observacao = forms.CharField(required=True,
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):
row1 = crispy_layout_mixin.to_row(
@ -234,7 +275,7 @@ class ProtocoloDocumentForm(forms.Form):
*args, **kwargs)
class ProtocoloMateriaForm(forms.Form):
class ProtocoloMateriaForm(ModelForm):
NUMERACAO_CHOICES = [('1', _('Sequencial por Ano')),
('2', _('Sequencial Único'))]
@ -273,6 +314,17 @@ class ProtocoloMateriaForm(forms.Form):
widget=forms.Textarea,
label='Observação')
class Meta:
model = Protocolo
fields = ['numeracao',
'tipo_protocolo',
'tipo_materia',
'num_paginas',
'ementa',
'autor',
'observacao',
]
def __init__(self, *args, **kwargs):
row1 = crispy_layout_mixin.to_row(
@ -299,6 +351,7 @@ class ProtocoloMateriaForm(forms.Form):
form_actions(save_label=_('Protocolar Matéria'))
)
)
super(ProtocoloMateriaForm, self).__init__(
*args, **kwargs)

136
protocoloadm/views.py

@ -2,8 +2,6 @@ from datetime import date, datetime
from re import sub
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.db.models import Max
from django.http import HttpResponseRedirect
@ -17,7 +15,7 @@ from vanilla import GenericView
from crud import Crud, make_pagination
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,
DocumentoAdministrativoForm, ProposicaoSimpleForm,
@ -47,13 +45,6 @@ class ProtocoloPesquisaView(FormView):
context_object_name = 'protocolos'
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):
form = ProtocoloForm(request.POST or None)
@ -124,74 +115,47 @@ class ProtocoloListView(ListView):
return context
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
class AnularProtocoloAdmView(FormValidMessageMixin, FormView):
class AnularProtocoloAdmView(FormView):
template_name = 'protocoloadm/anular_protocoloadm.html'
form_class = AnularProcoloAdmForm
success_url = reverse_lazy('anular_protocolo')
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):
form = AnularProcoloAdmForm(request.POST)
if form.is_valid():
numero = request.POST['numero_protocolo']
ano = request.POST['ano_protocolo']
justificativa_anulacao = sub(' ', ' ', strip_tags(
request.POST['justificativa_anulacao']))
numero = form.cleaned_data['numero']
ano = form.cleaned_data['ano']
user_anulacao = request.user.username
ip_addr = get_client_ip(request)
try:
protocolo = Protocolo.objects.get(numero=numero, ano=ano)
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.justificativa_anulacao = sub(' ', ' ', strip_tags(
form.cleaned_data['justificativa_anulacao']))
protocolo.user_anulacao = form.cleaned_data['user_anulacao']
protocolo.ip_anulacao = form.cleaned_data['ip_anulacao']
protocolo.save()
return self.form_valid(form)
except ObjectDoesNotExist:
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)
return self.form_valid(form)
else:
return self.form_invalid(form)
class ProtocoloDocumentoView(FormMixin, GenericView):
class ProtocoloDocumentoView(FormValidMessageMixin, CreateView):
template_name = "protocoloadm/protocolar_documento.html"
model = Protocolo
form_class = ProtocoloDocumentForm
def get_success_url(self):
return reverse('protocolo')
def get(self, request, *args, **kwargs):
form = ProtocoloDocumentForm()
return self.render_to_response({'form': form})
success_url = reverse_lazy('protocolo')
form_valid_message = _('Protocolo cadastrado com sucesso!')
def post(self, request, *args, **kwargs):
@ -207,7 +171,7 @@ class ProtocoloDocumentoView(FormMixin, GenericView):
if numeracao['numero__max'] is None:
numeracao['numero__max'] = 0
protocolo = Protocolo()
protocolo = form.save(commit=False)
protocolo.numero = numeracao['numero__max'] + 1
protocolo.ano = datetime.now().year
protocolo.data = datetime.now().strftime("%Y-%m-%d")
@ -224,19 +188,36 @@ class ProtocoloDocumentoView(FormMixin, GenericView):
protocolo.numero_paginas = request.POST['num_paginas']
protocolo.observacao = sub(
' ', ' ', strip_tags(request.POST['observacao']))
protocolo.save()
return self.form_valid(form)
else:
return self.form_invalid(form)
def criar_documento(protocolo):
doc = {}
class CriarDocumentoProtocolo(CreateView):
template_name = "protocoloadm/criar_documento.html"
form_class = DocumentoAdministrativoForm
def get_initial(self):
numero = self.kwargs['pk']
ano = self.kwargs['ano']
protocolo = Protocolo.objects.get(ano=ano, numero=numero)
return self.criar_documento(protocolo)
def get_success_url(self):
return reverse('protocolo_mostrar', kwargs={'pk': self.kwargs['pk'],
'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
@ -246,41 +227,29 @@ def criar_documento(protocolo):
doc['numero'] = numero['numero__max']
if doc['numero'] is None:
doc['numero'] = 1
return doc
class CriarDocumentoProtocolo(CreateView):
template_name = "protocoloadm/criar_documento.html"
form_class = DocumentoAdministrativoForm
def get_initial(self):
numero = self.kwargs['pk']
ano = self.kwargs['ano']
protocolo = Protocolo.objects.get(ano=ano, numero=numero)
return criar_documento(protocolo)
def get_success_url(self):
return reverse('protocolo_mostrar', kwargs={'pk': self.kwargs['pk'],
'ano': self.kwargs['ano']})
class ProtocoloMostrarView(TemplateView):
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']
ano = self.kwargs['ano']
protocolo = Protocolo.objects.get(ano=ano, numero=numero)
return self.render_to_response({"protocolo": protocolo})
context['protocolo'] = protocolo
return context
class ComprovanteProtocoloView(TemplateView):
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']
ano = self.kwargs['ano']
protocolo = Protocolo.objects.get(ano=ano, numero=numero)
@ -295,20 +264,21 @@ class ComprovanteProtocoloView(TemplateView):
protocolo.data.strftime("%Y/%m/%d") + \
str(protocolo.numero).zfill(6)
return self.render_to_response({"protocolo": protocolo,
context.update({"protocolo": protocolo,
"barcode": barcode,
"autenticacao": autenticacao})
return context
class ProtocoloMateriaView(FormMixin, GenericView):
class ProtocoloMateriaView(FormValidMessageMixin, CreateView):
template_name = "protocoloadm/protocolar_materia.html"
model = Protocolo
form_class = ProtocoloMateriaForm
form_valid_message = _('Matéria cadastrada com sucesso!')
def get(self, request, *args, **kwargs):
form = ProtocoloMateriaForm()
return self.render_to_response({'form': form})
def get_initial(self):
initial = {}
return initial
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)
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):
# TODO substituir por Site.objects.get_current().domain
# from django.contrib.sites.models import Site

Loading…
Cancel
Save