diff --git a/norma/forms.py b/norma/forms.py index 87e19e529..c14fae6cb 100644 --- a/norma/forms.py +++ b/norma/forms.py @@ -24,14 +24,77 @@ class HorizontalRadioRenderer(forms.RadioSelect.renderer): return mark_safe(u' '.join([u'%s ' % w for w in self])) +class NormaJuridicaPesquisaForm(ModelForm): + + periodo_inicial = forms.DateField(label=u'Período Inicial', + input_formats=['%d/%m/%Y'], + required=False, + widget=forms.DateInput( + format='%d/%m/%Y', + attrs={'class': 'dateinput'})) + + periodo_final = forms.DateField(label=u'Período Final', + input_formats=['%d/%m/%Y'], + required=False, + widget=forms.DateInput( + format='%d/%m/%Y', + attrs={'class': 'dateinput'})) + + publicação_inicial = forms.DateField(label=u'Publicação Inicial', + input_formats=['%d/%m/%Y'], + required=False, + widget=forms.DateInput( + format='%d/%m/%Y', + attrs={'class': 'dateinput'})) + + publicação_final = forms.DateField(label=u'Publicação Final', + input_formats=['%d/%m/%Y'], + required=False, + widget=forms.DateInput( + format='%d/%m/%Y', + attrs={'class': 'dateinput'})) + + class Meta: + model = NormaJuridica + fields = ['tipo', + 'numero', + 'ano', + 'periodo_inicial', + 'periodo_final', + 'publicação_inicial', + 'publicação_final'] + + def __init__(self, *args, **kwargs): + + row1 = crispy_layout_mixin.to_row( + [('tipo', 12)]) + + row2 = crispy_layout_mixin.to_row( + [('numero', 6), ('ano', 6)]) + + row3 = crispy_layout_mixin.to_row( + [('periodo_inicial', 6), ('periodo_final', 6)]) + + row4 = crispy_layout_mixin.to_row( + [('publicação_inicial', 6), ('publicação_final', 6)]) + + self.helper = FormHelper() + self.helper.layout = Layout( + Fieldset('Pesquisa Norma Juridica', + row1, row2, row3, row4), + form_actions(save_label='Pesquisar') + ) + super(NormaJuridicaPesquisaForm, self).__init__(*args, **kwargs) + + class NormaJuridicaForm(ModelForm): tipo_materia = forms.ModelChoiceField( - label=_('Matéria Legislativa'), + label='Matéria Legislativa', required=False, queryset=TipoMateriaLegislativa.objects.all(), empty_label='Selecione' - ) + ) numero_materia = forms.CharField(label='Número', required=False) @@ -55,30 +118,23 @@ class NormaJuridicaForm(ModelForm): 'ementa', 'indexacao', 'observacao', - 'texto_integral'] + 'texto_integral', + ] def __init__(self, *args, **kwargs): row1 = crispy_layout_mixin.to_row( - [('tipo', 4), - ('numero', 4), - ('ano', 4)]) + [('tipo', 4), ('numero', 4), ('ano', 4)]) row2 = crispy_layout_mixin.to_row( - [('data', 4), - ('esfera_federacao', 4), - ('complemento', 4)]) + [('data', 4), ('esfera_federacao', 4), ('complemento', 4)]) row3 = crispy_layout_mixin.to_row( - [('tipo_materia', 4), - ('numero_materia', 4), - ('ano_materia', 4)]) + [('tipo_materia', 4), ('numero_materia', 4), ('ano_materia', 4)]) row4 = crispy_layout_mixin.to_row( - [('data_publicacao', 3), - ('veiculo_publicacao', 3), - ('pagina_inicio_publicacao', 3), - ('pagina_fim_publicacao', 3)]) + [('data_publicacao', 3), ('veiculo_publicacao', 3), + ('pagina_inicio_publicacao', 3), ('pagina_fim_publicacao', 3)]) row5 = crispy_layout_mixin.to_row( [('texto_integral', 12)]) @@ -94,10 +150,8 @@ class NormaJuridicaForm(ModelForm): self.helper = FormHelper() self.helper.layout = Layout( - Fieldset(_('Cadastro de Norma Jurídica'), - Fieldset(_('Identificação Básica'), - row1, row2, row3, row4, row5, row6, row7, row8), - form_actions() - ) + Fieldset('Identificação Básica', + row1, row2, row3, row4, row5, row6, row7, row8), + form_actions() ) super(NormaJuridicaForm, self).__init__(*args, **kwargs) diff --git a/norma/migrations/0011_auto_20160307_1153.py b/norma/migrations/0011_auto_20160307_1153.py new file mode 100644 index 000000000..19631773d --- /dev/null +++ b/norma/migrations/0011_auto_20160307_1153.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9 on 2016-03-07 14:53 +from __future__ import unicode_literals + +import datetime +from django.db import migrations, models +from django.utils.timezone import utc + + +class Migration(migrations.Migration): + + dependencies = [ + ('norma', '0010_auto_20160216_1015'), + ] + + operations = [ + migrations.AlterField( + model_name='normajuridica', + name='data', + field=models.DateField(default=datetime.datetime(2016, 3, 7, 14, 53, 52, 206255, tzinfo=utc), verbose_name='Data'), + preserve_default=False, + ), + ] diff --git a/norma/models.py b/norma/models.py index 724a0ca75..b03264d64 100644 --- a/norma/models.py +++ b/norma/models.py @@ -81,7 +81,7 @@ class NormaJuridica(models.Model): max_length=1, verbose_name=_('Esfera Federação'), choices=ESFERA_FEDERACAO_CHOICES) - data = models.DateField(blank=True, null=True, verbose_name=_('Data')) + data = models.DateField(verbose_name=_('Data')) data_publicacao = models.DateField( blank=True, null=True, verbose_name=_('Data Publicação')) veiculo_publicacao = models.CharField( diff --git a/norma/urls.py b/norma/urls.py index b770223fa..888ce6747 100644 --- a/norma/urls.py +++ b/norma/urls.py @@ -1,7 +1,9 @@ from django.conf.urls import include, url -from norma.views import (NormaIncluirView, NormaTaView, assunto_norma_crud, - norma_temporario_crud, tipo_norma_crud) +from norma.views import (NormaEditView, NormaIncluirView, NormaPesquisaView, + NormaTaView, PesquisaNormaListView, + assunto_norma_crud, norma_temporario_crud, + tipo_norma_crud) # norma_url_patterns = norma_crud.urlpatterns + [] norma_url_patterns = norma_temporario_crud.urlpatterns + [ @@ -17,5 +19,11 @@ urlpatterns = [ url(r'^sistema/norma/tipo/', include(tipo_norma_crud.urls)), url(r'^sistema/norma/assunto/', include(assunto_norma_crud.urls)), - url(r'^norma/incluir', NormaIncluirView.as_view(), name='norma-incluir'), + url(r'^norma/incluir$', NormaIncluirView.as_view(), name='norma_incluir'), + url(r'^norma/(?P[0-9]+)/editar$', + NormaEditView.as_view(), name='norma_editar'), + url(r'^norma/pesquisa$', + NormaPesquisaView.as_view(), name='norma_pesquisa'), + url(r'^norma/pesquisa-resultado$', + PesquisaNormaListView.as_view(), name='list_pesquisa_norma'), ] diff --git a/norma/views.py b/norma/views.py index 113358ac7..452485d64 100644 --- a/norma/views.py +++ b/norma/views.py @@ -2,16 +2,20 @@ from datetime import datetime from re import sub from django.core.exceptions import ObjectDoesNotExist +from django.core.urlresolvers import reverse +from django.http import HttpResponseRedirect +from django.shortcuts import redirect from django.utils.html import strip_tags from django.utils.translation import ugettext_lazy as _ +from django.views.generic import CreateView, ListView from django.views.generic.edit import FormMixin from vanilla.views import GenericView from compilacao.views import IntegracaoTaView -from crud import Crud +from crud import Crud, make_pagination from materia.models import MateriaLegislativa, TipoMateriaLegislativa -from .forms import NormaJuridicaForm +from .forms import NormaJuridicaForm, NormaJuridicaPesquisaForm from .models import (AssuntoNorma, LegislacaoCitada, NormaJuridica, TipoNormaJuridica) @@ -22,54 +26,172 @@ norma_temporario_crud = Crud(NormaJuridica, 'normajuridica') legislacao_citada_crud = Crud(LegislacaoCitada, '') -class NormaIncluirView(FormMixin, GenericView): +class NormaPesquisaView(GenericView): + template_name = "norma/pesquisa.html" + + def get_success_url(self): + return reverse('normajuridica:norma_pesquisa') + + def get(self, request, *args, **kwargs): + form = NormaJuridicaPesquisaForm() + return self.render_to_response({'form': form}) + + def post(self, request, *args, **kwargs): + form = NormaJuridicaPesquisaForm(request.POST) + + if form.data['tipo']: + kwargs['tipo'] = form.data['tipo'] + if form.data['numero']: + kwargs['numero'] = form.data['numero'] + if form.data['ano']: + kwargs['ano'] = form.data['ano'] + if form.data['periodo_inicial'] and form.data['periodo_final']: + kwargs['periodo_inicial'] = form.data['periodo_inicial'] + kwargs['periodo_final'] = form.data['periodo_final'] + if form.data['publicação_inicial'] and form.data['publicação_final']: + kwargs['publicação_inicial'] = form.data['publicação_inicial'] + kwargs['publicação_final'] = form.data['publicação_final'] + + request.session['kwargs'] = kwargs + return redirect('list_pesquisa_norma') + + +class PesquisaNormaListView(ListView): + template_name = 'norma/list_pesquisa.html' + model = NormaJuridica + paginate_by = 10 + + def get_queryset(self): + kwargs = self.request.session['kwargs'] + normas = NormaJuridica.objects.all().order_by('-ano', '-numero') + + if 'periodo_inicial' and 'publicacao_inicial' in kwargs: + periodo_inicial = datetime.strptime( + kwargs['periodo_inicial'], + '%d/%m/%Y').strftime('%Y-%m-%d') + periodo_final = datetime.strptime( + kwargs['periodo_final'], + '%d/%m/%Y').strftime('%Y-%m-%d') + publicação_inicial = datetime.strptime( + kwargs['publicação_inicial'], + '%d/%m/%Y').strftime('%Y-%m-%d') + publicação_final = datetime.strptime( + kwargs['publicação_final'], + '%d/%m/%Y').strftime('%Y-%m-%d') + + normas = normas.filter( + data__range=(periodo_inicial, periodo_final), + data_publicacao__range=(publicação_inicial, publicação_final)) + + if 'periodo_inicial' in kwargs: + inicial = datetime.strptime(kwargs['periodo_inicial'], + '%d/%m/%Y').strftime('%Y-%m-%d') + final = datetime.strptime(kwargs['periodo_inicial'], + '%d/%m/%Y').strftime('%Y-%m-%d') + + normas = normas.filter(data__range=(inicial, final)) + + if 'publicação_inicial' in kwargs: + inicial = datetime.strptime(kwargs['publicação_inicial'], + '%d/%m/%Y').strftime('%Y-%m-%d') + final = datetime.strptime(kwargs['publicação_final'], + '%d/%m/%Y').strftime('%Y-%m-%d') + + normas = normas.filter(data_publicacao__range=(inicial, final)) + if 'tipo' in kwargs: + normas = normas.filter(tipo=kwargs['tipo']) + + if 'numero' in kwargs: + normas = normas.filter(numero=kwargs['numero']) + + if 'ano' in kwargs: + normas = normas.filter(ano=kwargs['ano']) + + return normas + + def get_context_data(self, **kwargs): + context = super(PesquisaNormaListView, self).get_context_data( + **kwargs) + + paginator = context['paginator'] + page_obj = context['page_obj'] + + context['page_range'] = make_pagination( + page_obj.number, paginator.num_pages) + return context + + +class NormaIncluirView(CreateView): template_name = "norma/normajuridica_incluir.html" + form_class = NormaJuridicaForm def get_success_url(self): - return '/norma/' + return reverse('normajuridica:list') def get(self, request, *args, **kwargs): form = NormaJuridicaForm() return self.render_to_response({'form': form}) def post(self, request, *args, **kwargs): - form = NormaJuridicaForm(request.POST or None) + form = self.get_form() + if form.is_valid(): norma = form.save(commit=False) if form.cleaned_data['tipo_materia']: - tipo = TipoMateriaLegislativa.objects.get( - id=form.cleaned_data['tipo_materia']) try: materia = MateriaLegislativa.objects.get( - tipo=tipo, - numero=form.cleaned_data['numero'], - ano=form.cleaned_data['ano']) + tipo_id=form.cleaned_data['tipo_materia'], + numero=form.cleaned_data['numero_materia'], + ano=form.cleaned_data['ano_materia']) except ObjectDoesNotExist: - return self.render_to_response( - {'form': form, - 'error': _('Matéria adicionada não existe!')}) + msg = 'Matéria adicionada não existe!' + messages.add_message(request, messages.INFO, msg) + return self.render_to_response({'form': form}) else: norma.materia = materia + norma.timestamp = datetime.now() + norma.save() + return HttpResponseRedirect(self.get_success_url()) + else: + return self.render_to_response({'form': form}) + - if form.cleaned_data['indexacao']: - norma.indexacao = sub( - ' ', ' ', strip_tags(form.cleaned_data['indexacao'])) +class NormaEditView(CreateView): + template_name = "norma/normajuridica_incluir.html" + form_class = NormaJuridicaForm - if form.cleaned_data['observacao']: - norma.observacao = sub( - ' ', ' ', strip_tags(form.cleaned_data['observacao'])) + def get(self, request, *args, **kwargs): + norma = NormaJuridica.objects.get(id=self.kwargs['pk']) + form = NormaJuridicaForm(instance=norma) + return self.render_to_response({'form': form}) - if 'texto_integral' in request.FILES: - norma.texto_integral = request.FILES['texto_integral'] + def post(self, request, *args, **kwargs): + norma = NormaJuridica.objects.get(id=self.kwargs['pk']) + form = NormaJuridicaForm(instance=norma, data=request.POST) - norma.ementa = sub( - ' ', ' ', strip_tags(form.cleaned_data['ementa'])) + if form.is_valid(): + if form.data['tipo_materia']: + try: + materia = MateriaLegislativa.objects.get( + tipo_id=form.data['tipo_materia'], + numero=form.data['numero_materia'], + ano=form.data['ano_materia']) + except ObjectDoesNotExist: + msg = 'Matéria adicionada não existe!' + messages.add_message(request, messages.INFO, msg) + return self.render_to_response({'form': form}) + else: + norma.materia = materia + norma = form.save(commit=False) norma.timestamp = datetime.now() norma.save() - return self.form_valid(form) + return HttpResponseRedirect(self.get_success_url()) else: - return self.form_invalid(form) + return self.render_to_response({'form': form}) + + def get_success_url(self): + return reverse('normajuridica:list') class NormaTaView(IntegracaoTaView): diff --git a/templates/base.html b/templates/base.html index 6803a4db3..94a6b4357 100644 --- a/templates/base.html +++ b/templates/base.html @@ -81,7 +81,7 @@ diff --git a/templates/norma/list_pesquisa.html b/templates/norma/list_pesquisa.html new file mode 100644 index 000000000..e4a1bb020 --- /dev/null +++ b/templates/norma/list_pesquisa.html @@ -0,0 +1,36 @@ +{% extends "crud/detail.html" %} +{% load i18n %} +{% load crispy_forms_tags %} +{% block actions %}{% endblock %} +{% block detail_content %} +
+ Adicionar Norma Jurídica +
+


+ {% if object_list %} + + + + + + + + + + + {% for obj in object_list %} + + + + + + + + {% endfor %} +
Tipo da Norma JuridicaNúmeroAnoDataEmenta
{{obj.tipo}}{{obj.numero}}{{obj.ano}}{{obj.data}}{{obj.ementa|safe}}
+ {% include "paginacao.html" %} + {% else %} +

Nenhum Registro recuperado

+ {% endif %} + +{% endblock detail_content %} diff --git a/templates/norma/normajuridica_detail.html b/templates/norma/normajuridica_detail.html index 1b0b041b8..7487ff7cc 100644 --- a/templates/norma/normajuridica_detail.html +++ b/templates/norma/normajuridica_detail.html @@ -17,3 +17,12 @@ {% endblock sections_nav %} + +
+ {% block actions %} + + {% endblock actions %} +
diff --git a/templates/norma/normajuridica_incluir.html b/templates/norma/normajuridica_incluir.html index 15a058275..42eb54de9 100644 --- a/templates/norma/normajuridica_incluir.html +++ b/templates/norma/normajuridica_incluir.html @@ -1,8 +1,3 @@ -{% extends "norma/normajuridica_detail.html" %} +{% extends "crud/form.html" %} {% load i18n %} {% load crispy_forms_tags %} - -{% block detail_content %} - {% if error %}
{{ error }}
{% endif %} - {% crispy form %} -{% endblock %} \ No newline at end of file diff --git a/templates/norma/normajuridica_list.html b/templates/norma/normajuridica_list.html new file mode 100644 index 000000000..6d5431bd5 --- /dev/null +++ b/templates/norma/normajuridica_list.html @@ -0,0 +1,36 @@ +{% extends "crud/list.html" %} +{% load i18n %} +{% load crispy_forms_tags %} +{% block base_content %} +
+ + {% blocktrans with verbose_name=view.verbose_name %} Adicionar {{ verbose_name }} {% endblocktrans %} + +
+


+ {% if object_list %} + + + + + + + + + + + {% for obj in object_list %} + + + + + + + + {% endfor %} +
Tipo da Norma JuridicaNúmeroAnoDataEmenta
{{obj.tipo}}{{obj.numero}}{{obj.ano}}{{obj.data}}{{obj.ementa|safe}}
+ {% include "paginacao.html" %} + {% else %} +

Nenhum Registro recuperado

+ {% endif %} +{% endblock %} diff --git a/templates/norma/pesquisa.html b/templates/norma/pesquisa.html new file mode 100644 index 000000000..42eb54de9 --- /dev/null +++ b/templates/norma/pesquisa.html @@ -0,0 +1,3 @@ +{% extends "crud/form.html" %} +{% load i18n %} +{% load crispy_forms_tags %}