Browse Source

Merge pull request #585 from interlegis/580-criar-tabela-app-config

Fix #580 criar tabela app config
pull/588/merge
Edward 8 years ago
committed by GitHub
parent
commit
2a08a7ddd1
  1. 10
      sapl/base/forms.py
  2. 24
      sapl/base/migrations/0017_appconfig.py
  3. 33
      sapl/base/models.py
  4. 6
      sapl/base/urls.py
  5. 36
      sapl/base/views.py
  6. 38
      sapl/protocoloadm/forms.py
  7. 45
      sapl/protocoloadm/views.py
  8. 4
      sapl/templates/base/layouts.yaml
  9. 1
      sapl/templates/sistema.html

10
sapl/base/forms.py

@ -15,7 +15,7 @@ from sapl.settings import MAX_IMAGE_UPLOAD_SIZE
from sapl.utils import (RANGE_ANOS, ImageThumbnailFileInput, autor_label, from sapl.utils import (RANGE_ANOS, ImageThumbnailFileInput, autor_label,
autor_modal) autor_modal)
from .models import CasaLegislativa from .models import AppConfig, CasaLegislativa
class RangeWidgetOverride(forms.MultiWidget): class RangeWidgetOverride(forms.MultiWidget):
@ -284,3 +284,11 @@ class LoginForm(AuthenticationForm):
widget=forms.PasswordInput( widget=forms.PasswordInput(
attrs={ attrs={
'class': 'form-control', 'name': 'password'})) 'class': 'form-control', 'name': 'password'}))
class ConfiguracoesAppForm(ModelForm):
class Meta:
model = AppConfig
fields = ['documentos_administrativos',
'sequencia_numeracao',
'painel_aberto']

24
sapl/base/migrations/0017_appconfig.py

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-15 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0016_auto_20160701_0940'),
]
operations = [
migrations.CreateModel(
name='AppConfig',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('documentos_administrativos', models.CharField(blank=True, choices=[('O', 'Ostensivo'), ('R', 'Restritivo')], max_length=1, null=True, verbose_name='Ostensivo/Restritivo')),
('sequencia_numeracao', models.CharField(blank=True, choices=[('A', 'Sequencial por ano'), ('U', 'Sequencial único')], max_length=1, null=True, verbose_name='Sequência de numeração')),
('painel_aberto', models.BooleanField(choices=[(True, 'Sim'), (False, 'Não')], verbose_name='Painel aberto para usuário anônimo')),
],
),
]

33
sapl/base/models.py

@ -3,7 +3,14 @@ from django.contrib.contenttypes.models import ContentType
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from sapl.utils import UF from sapl.utils import UF, YES_NO_CHOICES
TIPO_DOCUMENTO_ADMINISTRATIVO = (('O', _('Ostensivo')),
('R', _('Restritivo')))
SEQUENCIA_NUMERACAO = (('A', _('Sequencial por ano')),
('U', _('Sequencial único')))
def get_sessao_media_path(instance, subpath, filename): def get_sessao_media_path(instance, subpath, filename):
@ -68,3 +75,27 @@ class ProblemaMigracao(models.Model):
class Meta: class Meta:
verbose_name = _('Problema na Migração') verbose_name = _('Problema na Migração')
verbose_name_plural = _('Problemas na Migração') verbose_name_plural = _('Problemas na Migração')
class AppConfig(models.Model):
documentos_administrativos = models.CharField(
max_length=1,
verbose_name=_('Ostensivo/Restritivo'),
choices=TIPO_DOCUMENTO_ADMINISTRATIVO)
sequencia_numeracao = models.CharField(
max_length=1,
verbose_name=_('Sequência de numeração'),
choices=SEQUENCIA_NUMERACAO)
painel_aberto = models.BooleanField(
verbose_name=_('Painel aberto para usuário anônimo'),
choices=YES_NO_CHOICES)
class Meta:
verbose_name = _('Configurações da Aplicação')
verbose_name_plural = _('Configurações da Aplicação')
def __str__(self):
return _('Configurações da Aplicação - %(id)s') % {
'id': self.id}

6
sapl/base/urls.py

@ -4,7 +4,8 @@ from django.views.generic.base import TemplateView
from .apps import AppConfig from .apps import AppConfig
from .forms import LoginForm from .forms import LoginForm
from .views import (CasaLegislativaCrud, HelpView, RelatorioAtasView, from .views import (AppConfigCrud,
CasaLegislativaCrud, HelpView, RelatorioAtasView,
RelatorioHistoricoTramitacaoView, RelatorioHistoricoTramitacaoView,
RelatorioMateriasPorAnoAutorTipoView, RelatorioMateriasPorAnoAutorTipoView,
RelatorioMateriasPorAutorView, RelatorioMateriasPorAutorView,
@ -22,7 +23,8 @@ urlpatterns = [
url(r'^ajuda/(?P<topic>\w+)$', HelpView.as_view(), name='help_topic'), url(r'^ajuda/(?P<topic>\w+)$', HelpView.as_view(), name='help_topic'),
url(r'^ajuda/', TemplateView.as_view(template_name='ajuda/index.html'), url(r'^ajuda/', TemplateView.as_view(template_name='ajuda/index.html'),
name='help_base'), name='help_base'),
url(r'^casa_legislativa/', include(CasaLegislativaCrud.get_urls())), url(r'^casa-legislativa/', include(CasaLegislativaCrud.get_urls())),
url(r'^app-config/', include(AppConfigCrud.get_urls())),
url(r'^login/$', views.login, { url(r'^login/$', views.login, {
'template_name': 'base/login.html', 'authentication_form': LoginForm}, 'template_name': 'base/login.html', 'authentication_form': LoginForm},

36
sapl/base/views.py

@ -4,6 +4,7 @@ from django.db.models import Count, Q
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.views.generic.base import TemplateView from django.views.generic.base import TemplateView
from django.views.generic.edit import BaseCreateView
from django_filters.views import FilterView from django_filters.views import FilterView
from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView, from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView,
@ -13,13 +14,14 @@ from sapl.parlamentares.models import Parlamentar
from sapl.sessao.models import OrdemDia, SessaoPlenaria from sapl.sessao.models import OrdemDia, SessaoPlenaria
from sapl.utils import permissao_tb_aux from sapl.utils import permissao_tb_aux
from .forms import (CasaLegislativaForm, RelatorioAtasFilterSet, from .forms import (CasaLegislativaForm, ConfiguracoesAppForm,
RelatorioAtasFilterSet,
RelatorioHistoricoTramitacaoFilterSet, RelatorioHistoricoTramitacaoFilterSet,
RelatorioMateriasPorAnoAutorTipoFilterSet, RelatorioMateriasPorAnoAutorTipoFilterSet,
RelatorioMateriasPorAutorFilterSet, RelatorioMateriasPorAutorFilterSet,
RelatorioMateriasTramitacaoilterSet, RelatorioMateriasTramitacaoilterSet,
RelatorioPresencaSessaoFilterSet) RelatorioPresencaSessaoFilterSet)
from .models import CasaLegislativa from .models import AppConfig, CasaLegislativa
def get_casalegislativa(): def get_casalegislativa():
@ -261,3 +263,33 @@ class SistemaView(PermissionRequiredMixin, TemplateView):
def has_permission(self): def has_permission(self):
return permissao_tb_aux(self) return permissao_tb_aux(self)
class AppConfigCrud(Crud):
model = AppConfig
help_path = ''
class BaseMixin(PermissionRequiredMixin, CrudBaseMixin):
list_field_names = ['documentos_administrativos',
'sequencia_numeracao',
'painel_aberto']
def has_permission(self):
return permissao_tb_aux(self)
class CreateView(PermissionRequiredMixin, CrudCreateView):
form_class = ConfiguracoesAppForm
def get(self, request, *args, **kwargs):
app_config = AppConfig.objects.last()
if app_config:
return HttpResponseRedirect(
reverse('sapl.base:appconfig_update',
kwargs={'pk': app_config.pk}))
else:
self.object = None
return super(BaseCreateView, self).get(
request, *args, **kwargs)
class UpdateView(PermissionRequiredMixin, CrudUpdateView):
form_class = ConfiguracoesAppForm

38
sapl/protocoloadm/forms.py

@ -299,13 +299,6 @@ class AnularProcoloAdmForm(ModelForm):
class ProtocoloDocumentForm(ModelForm): class ProtocoloDocumentForm(ModelForm):
NUMERACAO_CHOICES = [('1', _('Sequencial por Ano')),
('2', _('Sequencial Único'))]
numeracao = forms.ChoiceField(required=True,
choices=NUMERACAO_CHOICES,
label='')
tipo_protocolo = forms.ChoiceField(required=True, tipo_protocolo = forms.ChoiceField(required=True,
label=_('Tipo de Protocolo'), label=_('Tipo de Protocolo'),
choices=TIPOS_PROTOCOLO,) choices=TIPOS_PROTOCOLO,)
@ -329,8 +322,7 @@ class ProtocoloDocumentForm(ModelForm):
class Meta: class Meta:
model = Protocolo model = Protocolo
fields = ['numeracao', fields = ['tipo_protocolo',
'tipo_protocolo',
'tipo_documento', 'tipo_documento',
'num_paginas', 'num_paginas',
'assunto', 'assunto',
@ -341,28 +333,25 @@ class ProtocoloDocumentForm(ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
row1 = to_row( row1 = to_row(
[(InlineRadios('numeracao'), 12)])
row2 = to_row(
[(InlineRadios('tipo_protocolo'), 12)]) [(InlineRadios('tipo_protocolo'), 12)])
row3 = to_row( row2 = to_row(
[('tipo_documento', 6), [('tipo_documento', 6),
('num_paginas', 6)]) ('num_paginas', 6)])
row4 = to_row( row3 = to_row(
[('assunto', 12)]) [('assunto', 12)])
row5 = to_row( row4 = to_row(
[('interessado', 12)]) [('interessado', 12)])
row6 = to_row( row5 = to_row(
[('observacao', 12)]) [('observacao', 12)])
self.helper = FormHelper() self.helper = FormHelper()
self.helper.layout = Layout( self.helper.layout = Layout(
Fieldset(_('Protocolo - Opção de Numeração'), row1),
Fieldset(_('Identificação de Documento'), Fieldset(_('Identificação de Documento'),
row1,
row2, row2,
row3, row3,
row4, row4,
row5, row5,
row6,
HTML("&nbsp;"), HTML("&nbsp;"),
form_actions(save_label=_('Protocolar Documento')) form_actions(save_label=_('Protocolar Documento'))
) )
@ -373,13 +362,6 @@ class ProtocoloDocumentForm(ModelForm):
class ProtocoloMateriaForm(ModelForm): class ProtocoloMateriaForm(ModelForm):
NUMERACAO_CHOICES = [('1', 'Sequencial por Ano'),
('2', 'Sequencial Único')]
numeracao = forms.ChoiceField(required=True,
choices=NUMERACAO_CHOICES,
label='')
tipo_protocolo = forms.ChoiceField(required=True, tipo_protocolo = forms.ChoiceField(required=True,
label='Tipo de Protocolo', label='Tipo de Protocolo',
choices=TIPOS_PROTOCOLO,) choices=TIPOS_PROTOCOLO,)
@ -398,8 +380,7 @@ class ProtocoloMateriaForm(ModelForm):
class Meta: class Meta:
model = Protocolo model = Protocolo
fields = ['numeracao', fields = ['tipo_protocolo',
'tipo_protocolo',
'tipo_materia', 'tipo_materia',
'numero_paginas', 'numero_paginas',
'autor', 'autor',
@ -408,10 +389,9 @@ class ProtocoloMateriaForm(ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
row1 = to_row( row1 = to_row(
[(InlineRadios('numeracao'), 12)]) [(InlineRadios('tipo_protocolo'), 12)])
row2 = to_row( row2 = to_row(
[('tipo_materia', 4), [('tipo_materia', 4),
(InlineRadios('tipo_protocolo'), 4),
('numero_paginas', 4)]) ('numero_paginas', 4)])
row3 = to_row( row3 = to_row(
[('autor', 0), [('autor', 0),
@ -426,8 +406,8 @@ class ProtocoloMateriaForm(ModelForm):
self.helper = FormHelper() self.helper = FormHelper()
self.helper.layout = Layout( self.helper.layout = Layout(
Fieldset(_('Protocolo - Opção de Numeração'), row1),
Fieldset(_('Identificação da Matéria'), Fieldset(_('Identificação da Matéria'),
row1,
row2, row2,
HTML(autor_label), HTML(autor_label),
HTML(autor_modal), HTML(autor_modal),

45
sapl/protocoloadm/views.py

@ -2,6 +2,7 @@ import json
from datetime import date, datetime from datetime import date, datetime
from braces.views import FormValidMessageMixin from braces.views import FormValidMessageMixin
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
@ -13,6 +14,8 @@ 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 django_filters.views import FilterView
from sapl.base.models import AppConfig
import sapl.crud.base import sapl.crud.base
from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView, from sapl.crud.base import (Crud, CrudBaseMixin, CrudCreateView,
CrudDeleteView, CrudListView, CrudUpdateView, CrudDeleteView, CrudListView, CrudUpdateView,
@ -206,18 +209,26 @@ class ProtocoloDocumentoView(PermissionRequiredMixin,
def form_valid(self, form): def form_valid(self, form):
f = form.save(commit=False) f = form.save(commit=False)
if form.cleaned_data['numeracao'] == '1': try:
numeracao = Protocolo.objects.filter( numeracao = AppConfig.objects.last().sequencia_numeracao
except AttributeError:
msg = _('É preciso definir a sequencia de ' +
'numeração na tabelas auxiliares!')
messages.add_message(self.request, messages.ERROR, msg)
return self.render_to_response(self.get_context_data())
if numeracao == 'A':
numero = Protocolo.objects.filter(
ano=date.today().year).aggregate(Max('numero')) ano=date.today().year).aggregate(Max('numero'))
elif form.cleaned_data['numeracao'] == '2': elif numeracao == 'U':
numeracao = Protocolo.objects.all().aggregate(Max('numero')) numero = Protocolo.objects.all().aggregate(Max('numero'))
if numeracao['numero__max'] is None: if numero['numero__max'] is None:
numeracao['numero__max'] = 0 numero['numero__max'] = 0
f.tipo_processo = '0' # TODO validar o significado f.tipo_processo = '0' # TODO validar o significado
f.anulado = False f.anulado = False
f.numero = numeracao['numero__max'] + 1 f.numero = numero['numero__max'] + 1
f.ano = datetime.now().year f.ano = datetime.now().year
f.data = datetime.now().strftime('%Y-%m-%d') f.data = datetime.now().strftime('%Y-%m-%d')
f.hora = datetime.now().strftime('%H:%M') f.hora = datetime.now().strftime('%H:%M')
@ -319,18 +330,26 @@ class ProtocoloMateriaView(PermissionRequiredMixin, CreateView):
return reverse('sapl.protocoloadm:protocolo') return reverse('sapl.protocoloadm:protocolo')
def form_valid(self, form): def form_valid(self, form):
if self.request.POST['numeracao'] == '1': try:
numeracao = Protocolo.objects.filter( numeracao = AppConfig.objects.last().sequencia_numeracao
except AttributeError:
msg = _('É preciso definir a sequencia de ' +
'numeração na tabelas auxiliares!')
messages.add_message(self.request, messages.ERROR, msg)
return self.render_to_response(self.get_context_data())
if numeracao == 'A':
numero = Protocolo.objects.filter(
ano=date.today().year).aggregate(Max('numero')) ano=date.today().year).aggregate(Max('numero'))
else: elif numeracao == 'U':
numeracao = Protocolo.objects.all().aggregate(Max('numero')) numero = Protocolo.objects.all().aggregate(Max('numero'))
if numeracao is None: if numeracao is None:
numeracao['numero__max'] = 0 numero['numero__max'] = 0
protocolo = Protocolo() protocolo = Protocolo()
protocolo.numero = numeracao['numero__max'] + 1 protocolo.numero = numero['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")
protocolo.hora = datetime.now().strftime("%H:%M") protocolo.hora = datetime.now().strftime("%H:%M")

4
sapl/templates/base/layouts.yaml

@ -9,3 +9,7 @@ CasaLegislativa:
- endereco_web - endereco_web
- email - email
- informacao_geral - informacao_geral
AppConfig:
{% trans 'Configurações da Aplicação' %}:
- documentos_administrativos sequencia_numeracao painel_aberto

1
sapl/templates/sistema.html

@ -6,6 +6,7 @@
<h2>Configuração Inicial</h2> <h2>Configuração Inicial</h2>
<div class="row"> <div class="row">
<div class="col-md-6"><a href="{% url 'sapl.base:casalegislativa_list' %}" class="btn btn-link">Casa Legislativa</a></div> <div class="col-md-6"><a href="{% url 'sapl.base:casalegislativa_list' %}" class="btn btn-link">Casa Legislativa</a></div>
<div class="col-md-6"><a href="{% url 'sapl.base:appconfig_list' %}" class="btn btn-link">Configurações da Aplicação</a></div>
</div> </div>
<hr /> <hr />

Loading…
Cancel
Save