diff --git a/sigi/apps/casas/admin.py b/sigi/apps/casas/admin.py index 0589ea1..03a2aeb 100644 --- a/sigi/apps/casas/admin.py +++ b/sigi/apps/casas/admin.py @@ -122,8 +122,9 @@ class CasaLegislativaAdmin(admin.ModelAdmin): return export_csv(request) relatorio_csv.short_description = u"Exportar casa(s) selecionada(s) para CSV" - def adicionar_casas(self, request, queryset): - if request.session.has_key('carrinho_casas'): + def adicionar_casas(self, request, queryset): + if 'carrinho_casas' in request.session: + #if request.session.has_key('carrinho_casas'): q1 = len(request.session['carrinho_casas']) else: q1 = 0 diff --git a/sigi/apps/casas/reports.py b/sigi/apps/casas/reports.py index e64af08..ecd4812 100644 --- a/sigi/apps/casas/reports.py +++ b/sigi/apps/casas/reports.py @@ -65,22 +65,22 @@ class CasasLegislativasLabels(Report): self.page_size = A4 if formato == '3x9_etiqueta': - self.margin_top = 0.0*cm - self.margin_bottom = 0.0*cm - self.margin_left = 0.0*cm - self.margin_right = 0.0*cm - self.delta = 0.3 - self.start = 0.2 + self.margin_top = 0.0*cm + self.margin_bottom = 0.0*cm + self.margin_left = 0.0*cm + self.margin_right = 0.0*cm + self.delta = 0.3 + self.start = 0.2 else: - self.margin_top = 0.8*cm - self.margin_bottom = 0.8*cm - self.margin_left = 0.4*cm - self.margin_right = 0.4*cm - self.largura_etiqueta = 9.9 - self.altura_etiqueta = 5.6 - self.tamanho_fonte = 11 - self.altura_dados = 0.5 - self.y = 0.5 + self.margin_top = 0.8*cm + self.margin_bottom = 0.8*cm + self.margin_left = 0.4*cm + self.margin_right = 0.4*cm + self.largura_etiqueta = 9.9 + self.altura_etiqueta = 5.6 + self.tamanho_fonte = 11 + self.altura_dados = 0.5 + self.y = 0.5 my_elements = [ Label( diff --git a/sigi/apps/casas/views.py b/sigi/apps/casas/views.py index 2ab90fe..531fb25 100644 --- a/sigi/apps/casas/views.py +++ b/sigi/apps/casas/views.py @@ -2,8 +2,8 @@ from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from geraldo.generators import PDFGenerator -from sigi.apps.casas.models import CasaLegislativa +from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.reports import CasasLegislativasLabels from sigi.apps.casas.reports import CasasLegislativasLabelsSemPresidente from sigi.apps.casas.reports import CasasLegislativasReport diff --git a/sigi/apps/mesas/admin.py b/sigi/apps/mesas/admin.py index 62eb551..7fb7af4 100644 --- a/sigi/apps/mesas/admin.py +++ b/sigi/apps/mesas/admin.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- from django.contrib import admin from django.http import HttpResponse -from django.utils.html import escape, escapejs +from django.utils.html import escape from sigi.apps.mesas.models import (Legislatura, Coligacao, ComposicaoColigacao, SessaoLegislativa, MesaDiretora, Cargo, MembroMesaDiretora) diff --git a/sigi/apps/mesas/models.py b/sigi/apps/mesas/models.py index f6062cb..1bbd5c9 100644 --- a/sigi/apps/mesas/models.py +++ b/sigi/apps/mesas/models.py @@ -1,4 +1,4 @@ -# -*- coding: utf-8 -*- +# coding: utf-8 from django.db import models from sigi.apps.casas.models import CasaLegislativa @@ -6,7 +6,7 @@ class Legislatura(models.Model): casa_legislativa = models.ForeignKey(CasaLegislativa) numero = models.PositiveSmallIntegerField(u'número legislatura') data_inicio = models.DateField(u'início') - data_fim = models.DateField('fim') + data_fim = models.DateField(u'fim') data_eleicao = models.DateField(u'data da eleição') total_parlamentares = models.PositiveIntegerField(u"Total de parlamentares") diff --git a/sigi/apps/parlamentares/admin.py b/sigi/apps/parlamentares/admin.py index 24e2632..c7e0c72 100644 --- a/sigi/apps/parlamentares/admin.py +++ b/sigi/apps/parlamentares/admin.py @@ -1,8 +1,11 @@ # -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.contenttypes import generic +from django.http import HttpResponse, HttpResponseRedirect + from sigi.apps.contatos.models import Telefone from sigi.apps.parlamentares.models import Partido, Parlamentar, Mandato +from sigi.apps.parlamentares.views import adicionar_parlamentar_carrinho class MandatosInline(admin.TabularInline): model = Mandato @@ -23,6 +26,7 @@ class ParlamentarAdmin(admin.ModelAdmin): list_display = ('nome_completo', 'nome_parlamentar', 'sexo') list_display_links = ('nome_completo', 'nome_parlamentar') list_filter = ('nome_completo', 'nome_parlamentar') + actions = ['adiciona_parlamentar',] fieldsets = ( (None, { 'fields': ('nome_completo', 'nome_parlamentar', 'sexo'), @@ -38,6 +42,23 @@ class ParlamentarAdmin(admin.ModelAdmin): # raw_id_fields = ('municipio',) search_fields = ('nome_completo', 'nome_parlamentar', 'email', 'pagina_web',) + + def adiciona_parlamentar(self, request, queryset): + if request.session.has_key('carrinho_parlametar'): + q1 = len(request.session['carrinho_parlamentar']) + else: + q1 = 0 + adicionar_parlamentar_carrinho(request,queryset=queryset) + q2 = len(request.session['carrinho_parlamentar']) + quant = q2 - q1 + if quant: + self.message_user(request,"%s Parlamentares adicionados no carrinho" % (quant) ) + else: + self.message_user(request,"Os parlamentares selecionadas já foram adicionadas anteriormente" ) + return HttpResponseRedirect('.') + + adiciona_parlamentar.short_description = u"Armazenar parlamentar no carrinho para exportar" + class MandatoAdmin(admin.ModelAdmin): list_display = ('parlamentar', 'legislatura', 'partido', diff --git a/sigi/apps/parlamentares/models.py b/sigi/apps/parlamentares/models.py index a45743c..f91d594 100644 --- a/sigi/apps/parlamentares/models.py +++ b/sigi/apps/parlamentares/models.py @@ -12,6 +12,7 @@ class Partido(models.Model): def __unicode__(self): return '%s (%s)' % (unicode(self.nome), unicode(self.sigla)) + class Parlamentar(models.Model): SEXO_CHOICES = ( ('M', 'Masculino'), @@ -38,10 +39,9 @@ class Parlamentar(models.Model): null=True, ) email = models.EmailField('e-mail', blank=True) - pagina_web = models.URLField( - u'página web', blank=True, - verify_exists=False - ) + pagina_web = models.URLField(u'página web', + blank=True, + verify_exists=False) class Meta: ordering = ('nome_completo',) @@ -53,19 +53,6 @@ class Parlamentar(models.Model): return self.nome_completo -# logradouro = models.CharField(max_length=100, blank=True) -# bairro = models.CharField(max_length=40, blank=True) -# municipio = models.ForeignKey('contatos.Municipio', blank=True, null=True) -# cep = models.CharField( -# 'CEP', -# max_length=9, -# blank=True, -# help_text="Formato: XXXXX-XXX." -# ) -# telefones = generic.GenericRelation('contatos.Telefone') - - - class Mandato(models.Model): SUPLENCIA_CHOICES = ( ('T', 'Titular'), diff --git a/sigi/apps/parlamentares/reports.py b/sigi/apps/parlamentares/reports.py new file mode 100644 index 0000000..e78b1db --- /dev/null +++ b/sigi/apps/parlamentares/reports.py @@ -0,0 +1,541 @@ +# -*- coding: utf-8 -*- +from reportlab.lib.pagesizes import A4 +from reportlab.lib.units import cm +from reportlab.lib.enums import TA_CENTER, TA_RIGHT +from geraldo import Report, DetailBand, Label, ObjectValue, ManyElements, \ + ReportGroup, ReportBand, landscape, SubReport, BAND_WIDTH,SystemField + +from sigi.apps.relatorios.reports import ReportDefault + +from geraldo.graphics import Image + +def string_to_cm(texto): + tamanho = 0 + minEspeciais = { + 'f':0.1, + 'i':0.05, + 'j':0.05, + 'l':0.05, + 'm':0.2, + 'r':0.1, + 't':0.15, + } + maiuEspeciais = { + 'I':0.05, + 'J':0.15, + 'L':0.15, + 'P':0.15, + } + for c in texto: + if c > 'a' and c<'z': + if c in minEspeciais: + tamanho += minEspeciais[c] + else: + tamanho += 0.17 + else: + if c in maiuEspeciais: + tamanho += maiuEspeciais[c] + else: + tamanho += 0.2 + return tamanho + +class ParlamentaresLabels(Report): + """ + Usage example:: + + >>> from geraldo.generators import PDFGenerator + >>> queryset = CasaLegislativa.objects.filter(municipio__uf__sigla='MG') + >>> report = LabelsReport(queryset) + >>> report.generate_by(PDFGenerator, filename='./inline-detail-report.pdf') + + """ + formato = '' + y = 2 + largura_etiqueta = 7 + altura_etiqueta = 3.3 + tamanho_fonte = 6.4 + altura_dados = 0.3 #logradouro, bairro, municipio, cep + delta = start = 0.5 + + def __init__(self, queryset, formato): + super(ParlamentaresLabels, self).__init__(queryset=queryset) + self.formato = formato + self.page_size = A4 + + if formato == '3x9_etiqueta': + self.margin_top = 0.0*cm + self.margin_bottom = 0.0*cm + self.margin_left = -1*cm + self.margin_right = 0.0*cm + self.delta = 0.4 # espaçamento entre as "strings/linhas" da etiqueta + self.start = 0.2 # valor entre a margin top e a etiqueta + else: + self.margin_top = 0.8*cm + self.margin_bottom = 0.8*cm + self.margin_left = 0.4*cm + self.margin_right = 0.4*cm + self.largura_etiqueta = 9.9 + self.altura_etiqueta = 5.6 + self.tamanho_fonte = 11 + self.altura_dados = 0.5 + self.y = 0.5 + + my_elements = [ + Label( + text='A Sua Excelência o(a) Senhor(a)', + top=(self.start + self.delta)*cm, left=self.y*cm, width=(self.largura_etiqueta-self.y)*cm, + ), + ObjectValue( + attribute_name='nome_completo', + top=(self.start + 2*self.delta)*cm, left=self.y*cm, width=(self.largura_etiqueta-self.y)*cm, + get_value=lambda instance: + instance.nome_completo or "" + ), + ObjectValue( + attribute_name='logradouro', + top=(self.start + 3*self.delta)*cm, left=self.y*cm, width=(self.largura_etiqueta-self.y)*cm, + get_value=lambda instance: + logradouro_parlamentar(instance) + ), + ObjectValue( + attribute_name='bairro', + top=(self.start + 4*self.delta)*cm, left=self.y*cm, width=(self.largura_etiqueta-self.y)*cm, + get_value=lambda instance: + bairro_parlamentar(instance) + ), + ObjectValue( + attribute_name='municipio', + top=(self.start + 5*self.delta)*cm, left=self.y*cm, width=(self.largura_etiqueta-self.y)*cm, + get_value=lambda instance: + municipio_parlamentar(instance) + ), + ObjectValue( + attribute_name='cep', + top=(self.start + 6*self.delta)*cm, left=self.y*cm, width=(self.largura_etiqueta-self.y)*cm, + get_value=lambda instance: + cep_parlamentar(instance) + ), + ] + self.band_detail = DetailBand(width=(self.largura_etiqueta)*cm, height=(self.altura_etiqueta)*cm, margin_left = 0, margin_top = 0, margin_bottom=0.0*cm, margin_right = 0, elements=my_elements,display_inline=True, default_style={'fontName': 'Helvetica', 'fontSize': self.tamanho_fonte}) + +def logradouro_parlamentar(instance): + try: + return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.logradouro + except: + return "<>" + +def bairro_parlamentar(instance): + try: + return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.bairro + except: + return "<>" + +def municipio_parlamentar(instance): + try: + return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.municipio + except: + return "<>" + +def cep_parlamentar(instance): + try: + return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.cep + except: + return "<>" + + +class CasasLegislativasReport(ReportDefault): + title = u'Relatório de Casas Legislativas' + height = 80*cm + page_size = landscape(A4) + + class band_page_header(ReportDefault.band_page_header): + + label_top = ReportDefault.band_page_header.label_top + label_left = [0.3,1,5.5,11,17,22] + elements = list(ReportDefault.band_page_header.elements) + + elements = [ + Image(filename= ReportDefault.band_page_header.BASE_DIR + '/media/images/logo-interlegis.jpg', + left=23.5*cm,right=1*cm,top=0.1*cm,bottom=1*cm, + width=4.2*cm,height=3*cm, + ), + Image(filename= ReportDefault.band_page_header.BASE_DIR + '/media/images/logo-senado.png', + left=1*cm,right=1*cm,top=0.1*cm,bottom=1*cm, + width=3*cm,height=3*cm, + ), + Label(text="SENADO FEDERAL",top=1*cm,left=0,width=BAND_WIDTH, + style={'fontName': 'Helvetica-Bold','fontSize':14, 'alignment': TA_CENTER} + ), + Label(text="SINTER - Secretaria Especial do Interlegis",top=1.5*cm,left=0,width=BAND_WIDTH, + style={'fontName': 'Helvetica-Bold','fontSize':13, 'alignment': TA_CENTER} + ), + SystemField( + expression='%(report_title)s',top=2.5*cm,left=0,width=BAND_WIDTH, + style={'fontName': 'Helvetica-Bold','fontSize':14, 'alignment': TA_CENTER} + ), + Label( + text="UF", + left=label_left[0]*cm, + top=label_top, + ), + Label( + text="Municipio", + left=label_left[1]*cm, + top=label_top, + ), + Label( + text="Presidente", + left=label_left[2]*cm, + top=label_top, + ), + Label( + text="Endereço", + left=label_left[3]*cm, + top=label_top, + ), + Label( + text="Endereço na Internet", + left=label_left[4]*cm, + top=label_top, + ), + Label( + text="Email", + left=label_left[5]*cm, + top=label_top, + ), + + + ] + + + + class band_page_footer(ReportDefault.band_page_footer): + pass + + class band_detail(ReportDefault.band_detail): + + label_left = [0.3,1,5.5,11,17,22] + + elements=[ + ObjectValue( + attribute_name='municipio.uf.sigla', + left=label_left[0]*cm, + width=1*cm, + ), + ObjectValue( + attribute_name='municipio.nome', + left=label_left[1]*cm, + ), + ObjectValue( + attribute_name='presidente', + left=label_left[2]*cm, + ), + ObjectValue( + attribute_name='logradouro', + left=label_left[3]*cm, + get_value=lambda instance: instance.logradouro + ' - '+ instance.bairro, + ), + ObjectValue( + attribute_name='pagina_web', + left=label_left[4]*cm, + ), + ObjectValue( + attribute_name='email', + left=label_left[5]*cm, + ), + + ] + + groups = [ + ReportGroup(attribute_name='municipio.uf', + band_header=ReportBand( + height=0.7*cm, + elements= [ + ObjectValue(attribute_name='municipio.uf') + ], + borders={'top': True}, + ) + ) + ] + + +class InfoCasaLegislativa(ReportDefault): + title = u'Casa legislativa' + class band_summary(ReportBand): + pass + class band_page_footer(ReportBand): + height = 1*cm + + elements = [ + SystemField(expression=u'%(now:%d/%m/%Y)s às %(now:%H:%M)s', top=0.3*cm), + ] + + class band_detail(ReportDefault.band_detail): + + posicao_left = [ + 0,1.3, #Tipo + 0,1.8, #Regiao + 5.5,6.8, #U.F. + 0,2.3, #Municipio + 0,2.4, #Endereco + 0,1.6, #Bairro + 0,1.3, #CEP + 0,1.6, #CNPJ + 0,2.3, #Telefone + 0,2.7, #Presidente + ] + posicao_top = [ + 0.5, #Tipo + 1.3, #Regiao + 1.3, #U.F. + 2.1, #Municipio + 2.9, #Logradouro + 3.7, #Bairro + 4.5, #CEP + 5.3, #CNPJ + 6.1, #Telefone + 6.9, #Presidente + ] + + height=30*cm + + display_inline = True + default_style = {'fontName': 'Helvetica', 'fontSize':14} + + elements = [ + + Label( + text="Tipo: ", + left=posicao_left[0]*cm, + top=posicao_top[0]*cm, + ), + ObjectValue( + attribute_name='tipo.nome', + left=posicao_left[1]*cm, + top=posicao_top[0]*cm, + width=6*cm, + ), + Label( + text="Região: ", + left=posicao_left[2]*cm, + top=posicao_top[1]*cm, + ), + ObjectValue( + attribute_name='municipio.uf.regiao', + left=posicao_left[3]*cm, + top=posicao_top[1]*cm, + get_value=lambda instance: + {'SL': 'Sul','SD': 'Sudeste','CO': 'Centro-Oeste','NE': 'Nordeste','NO': 'Norte',} + [instance.municipio.uf.regiao] + ), + Label( + text="U.F.: ", + left=posicao_left[4]*cm, + top=posicao_top[2]*cm, + ), + ObjectValue( + attribute_name='municipio.uf', + left=posicao_left[5]*cm, + top=posicao_top[2]*cm, + ), + Label( + text="Município: ", + left=posicao_left[6]*cm, + top=posicao_top[3]*cm, + ), + ObjectValue( + attribute_name='municipio.nome', + left=posicao_left[7]*cm, + top=posicao_top[3]*cm, + width=20*cm, + ), + # Linha 3 + Label( + text="Endereço: ", + left=posicao_left[8]*cm, + top=posicao_top[4]*cm, + ), + ObjectValue( + attribute_name='logradouro', + left=posicao_left[9]*cm, + top=posicao_top[4]*cm, + width=20*cm, + ), + Label( + text="Bairro: ", + left=posicao_left[10]*cm, + top=posicao_top[5]*cm, + ), + ObjectValue( + attribute_name='bairro', + left=posicao_left[11]*cm, + top=posicao_top[5]*cm, + ), + Label( + text="CEP: ", + left=posicao_left[12]*cm, + top=posicao_top[6]*cm, + ), + ObjectValue( + attribute_name='cep', + left=posicao_left[13]*cm, + top=posicao_top[6]*cm, + ), + Label( + text="CNPJ: ", + left=posicao_left[14]*cm, + top=posicao_top[7]*cm, + ), + ObjectValue( + attribute_name='cnpj', + left=posicao_left[15]*cm, + top=posicao_top[7]*cm, + ), + Label( + text="Telefone: ", + left=posicao_left[16]*cm, + top=posicao_top[8]*cm, + ), + ObjectValue( + attribute_name='telefone', + left=posicao_left[17]*cm, + top=posicao_top[8]*cm, + ), + Label( + text="Presidente: ", + left=posicao_left[18]*cm, + top=posicao_top[9]*cm, + ), + ObjectValue( + attribute_name='presidente', + left=posicao_left[19]*cm, + top=posicao_top[9]*cm, + width=20*cm, + ), + ] + # Telefones + tel_top = 2*cm + tel_left = [0,3,5] + # Contato + cont_top = 2*cm + cont_left = [0,6,9] + # Convenios + convenio_top = 2*cm + convenio_left = [0,1.8,4.5,8,10.5,13,15.5,18] + subreports = [ + # Telefones + SubReport( + queryset_string = '%(object)s.telefones.all()', + band_header = ReportBand( + default_style = {'fontName': 'Helvetica', 'fontSize':12 }, + height=2.5*cm, + elements = [ + Label( + text="Telefone(s)", + style = {'fontSize':14,'alignment': TA_CENTER}, + width=BAND_WIDTH, + top=1*cm, + ), + Label(text="Número",left=tel_left[0]*cm,top=tel_top), + Label(text="Tipo",left=tel_left[1]*cm,top=tel_top), + Label(text="Nota",left=tel_left[2]*cm,top=tel_top), + ], + borders = {'bottom': True}, + ), + band_detail = ReportBand( + default_style = {'fontName': 'Helvetica', 'fontSize':11}, + height=0.5*cm, + elements= [ + ObjectValue(attribute_name='__unicode__',left=tel_left[0]*cm), + ObjectValue(attribute_name='tipo',left=tel_left[1]*cm, + get_value = lambda instance: + {'F':'Fixo','M':u'Móvel','X':'Fax','I':'Indefinido'}[instance.tipo], + ), + ObjectValue(attribute_name='nota',left=tel_left[2]*cm), + ], + #borders = {'all':True}, + ), + ), + #Contatos + SubReport( + queryset_string = '%(object)s.funcionario_set.all()', + band_header = ReportBand( + default_style = {'fontName': 'Helvetica', 'fontSize':12 }, + height=2.5*cm, + elements = [ + Label( + text="Contato(s)", + style = {'fontSize':14,'alignment': TA_CENTER}, + width=BAND_WIDTH, + top=1*cm, + ), + Label(text="Nome",left=cont_left[0]*cm,top=cont_top), + Label(text="Nota",left=cont_left[1]*cm,top=cont_top), + Label(text="E-mail",left=cont_left[2]*cm,top=cont_top), + ], + borders = {'bottom': True,'top':True}, + ), + band_detail = ReportBand( + default_style = {'fontName': 'Helvetica', 'fontSize':11}, + height=0.5*cm, + elements= [ + ObjectValue(attribute_name='nome',left=cont_left[0]*cm), + ObjectValue(attribute_name='nota',left=cont_left[1]*cm), + ObjectValue(attribute_name='email',left=cont_left[2]*cm), + ], + #borders = {'all':True}, + ), + ), + #Convenios + SubReport( + queryset_string = '%(object)s.convenio_set.all()', + band_header = ReportBand( + default_style = {'fontName': 'Helvetica', 'fontSize':12 }, + height=2.5*cm, + elements=[ + Label( + text="Convênio(s)", + style = {'fontSize':14,'alignment': TA_CENTER}, + width=BAND_WIDTH, + top=1*cm, + ), + Label(text="Projeto",left=convenio_left[0]*cm,top=convenio_top), + Label(text="Nº Convenio",left=convenio_left[1]*cm,top=convenio_top), + Label(text="Nº Processo SF",left=convenio_left[2]*cm,top=convenio_top), + Label(text="Adesão",left=convenio_left[3]*cm,top=convenio_top), + Label(text="Convênio",left=convenio_left[4]*cm,top=convenio_top), + Label(text="Equipada",left=convenio_left[5]*cm,top=convenio_top), + Label(text="Data D.O.",left=convenio_left[6]*cm,top=convenio_top), + ], + borders = {'bottom': True} + ), + band_detail = ReportBand( + default_style = {'fontName': 'Helvetica', 'fontSize':11}, + height=0.5*cm, + elements=[ + ObjectValue(attribute_name='projeto.sigla',left=convenio_left[0]*cm), + ObjectValue(attribute_name='num_convenio',left=convenio_left[1]*cm), + ObjectValue(attribute_name='num_processo_sf',left=convenio_left[2]*cm), + ObjectValue(attribute_name='data_adesao',left=convenio_left[3]*cm, + get_value=lambda instance: + instance.data_adesao.strftime('%d/%m/%Y') if instance.data_adesao != None else '-' + ), + ObjectValue(attribute_name='data_retorno_assinatura',left=convenio_left[4]*cm, + get_value=lambda instance: + instance.data_retorno_assinatura.strftime('%d/%m/%Y') if instance.data_retorno_assinatura != None else '-' + ), + ObjectValue(attribute_name='data_termo_aceite',left=convenio_left[5]*cm, + get_value=lambda instance: + instance.data_termo_aceite.strftime('%d/%m/%Y') if instance.data_termo_aceite != None else '-' + ), + ObjectValue(attribute_name='data_pub_diario',left=convenio_left[6]*cm, + get_value=lambda instance: + instance.data_pub_diario.strftime('%d/%m/%Y') if instance.data_pub_diario != None else '-' + ), + ], + #borders = {'all':True}, + ), + ) + ] + + diff --git a/sigi/apps/parlamentares/templates/parlamentares/carrinho.html b/sigi/apps/parlamentares/templates/parlamentares/carrinho.html new file mode 100644 index 0000000..a40b8fc --- /dev/null +++ b/sigi/apps/parlamentares/templates/parlamentares/carrinho.html @@ -0,0 +1,78 @@ +{% extends "admin/carrinho.html" %} +{% load adminmedia admin_list i18n %} +{% block extrastyle %} + {{ block.super }} + {% include "admin/tabs_style.html" %} + + +{% endblock %} + +{% block title %}Parlamentares no Carrinho | SIGI{% endblock %} +{% block content_title %}

Parlamentares no Carrinho

{% endblock %} + +{% block mensagem%} +
    + {%if carIsEmpty%} +
  • O carrinho está vazio, sendo assim todas as casas entram na lista para exportação de acordo com os filtros aplicados.
  • + {%else%} +
  • {{paginas.paginator.count}}Parlamentares no carrinho.
  • + {%endif%} +
+{% endblock %} + +{% block action %}deleta_itens_carrinho{% endblock %} + +{% block tabela %} + + + + {%if not carIsEmpty%} + + {% endif %} + + + + + + + {% for parlamentar in paginas.object_list %} + + {%if not carIsEmpty%} + + {% endif %} + + + + + {% endfor %} + +
+ NomeNome parlamentarSexo
{{parlamentar.nome_completo}}{{parlamentar.nome_parlamentar}}{{parlamentar.get_sexo_display}}
+{% endblock %} + +{% block botoes %} +
+ + +
+
{% csrf_token %} +
Formato da Etiqueta +
    +
  • +
  • + +
+
+
    +
  • +
+
+ +
+ +{% endblock %} diff --git a/sigi/apps/parlamentares/templates/parlamentares/change_form.html b/sigi/apps/parlamentares/templates/parlamentares/change_form.html new file mode 100644 index 0000000..b59cb99 --- /dev/null +++ b/sigi/apps/parlamentares/templates/parlamentares/change_form.html @@ -0,0 +1,14 @@ +{% extends "admin/change_form.html" %} +{% load i18n reporting_tags %} + +{% block object-tools %} +{% if change %}{% if not is_popup %} + +{% endif %}{% endif %} +{% endblock %} diff --git a/sigi/apps/parlamentares/templates/parlamentares/change_list.html b/sigi/apps/parlamentares/templates/parlamentares/change_list.html new file mode 100644 index 0000000..05501cd --- /dev/null +++ b/sigi/apps/parlamentares/templates/parlamentares/change_list.html @@ -0,0 +1,9 @@ +{% extends "admin/change_list.html" %} +{% load adminmedia admin_list i18n reporting_tags %} + +{% block object-tools %} + + +{% endblock %} diff --git a/sigi/apps/parlamentares/views.py b/sigi/apps/parlamentares/views.py new file mode 100644 index 0000000..8ae81b0 --- /dev/null +++ b/sigi/apps/parlamentares/views.py @@ -0,0 +1,149 @@ +# coding: utf-8 +import datetime +import csv +import ho.pisa as pisa + +from django.template import Context, loader +from django.core.paginator import Paginator, InvalidPage, EmptyPage +from django.conf import settings +from django.shortcuts import render_to_response, get_list_or_404 +from django.http import HttpResponse, HttpResponseRedirect +from django.views.decorators.csrf import csrf_protect +from django.template import RequestContext + +from sigi.apps.parlamentares.models import Parlamentar +from sigi.apps.parlamentares.reports import ParlamentaresLabels + +from geraldo.generators import PDFGenerator + + +def adicionar_parlamentar_carrinho(request,queryset=None,id=None): + if request.method == 'POST': + ids_selecionados = request.POST.getlist('_selected_action') + if not request.session.has_key('carrinho_parlametar'): + request.session['carrinho_parlamentar'] = ids_selecionados + else: + lista = request.session['carrinho_parlamentar'] + # Verifica se id já não está adicionado + for id in ids_selecionados: + if not id in lista: + lista.append(id) + request.session['carrinho_parlamentar'] = lista + + +@csrf_protect +def visualizar_carrinho(request): + + qs = carrinhoOrGet_for_qs(request) + + paginator = Paginator(qs, 100) + + # Make sure page request is an int. If not, deliver first page. + # Esteja certo de que o `page request` é um inteiro. Se não, mostre a primeira página. + try: + page = int(request.GET.get('page', '1')) + except ValueError: + page = 1 + + # Se o page request (9999) está fora da lista, mostre a última página. + try: + paginas = paginator.page(page) + except (EmptyPage, InvalidPage): + paginas = paginator.page(paginator.num_pages) + + carrinhoIsEmpty = not(request.session.has_key('carrinho_parlamentares')) + + return render_to_response('parlamentares/carrinho.html', + {"ADMIN_MEDIA_PREFIX":settings.ADMIN_MEDIA_PREFIX, + 'MEDIA_URL':settings.MEDIA_URL, + 'carIsEmpty':carrinhoIsEmpty, + 'paginas':paginas, + 'query_str':'?'+request.META['QUERY_STRING']}, + context_instance=RequestContext(request)) + + +def carrinhoOrGet_for_qs(request): + """ + Verifica se existe parlamentares na sessão se não verifica get e retorna qs correspondente. + """ + if request.session.has_key('carrinho_parlamentar'): + ids = request.session['carrinho_parlamentar'] + qs = Parlamentar.objects.filter(pk__in=ids) + else: + qs = Parlamentar.objects.all() + if request.GET: + qs = get_for_qs(request.GET,qs) + return qs + + +def query_ordena(qs,o,ot): + list_display = ('nome_completo',) + + aux = list_display[(int(o)-1)] + if ot =='asc': + qs = qs.order_by(aux) + else: + qs = qs.order_by("-"+aux) + return qs + + +def get_for_qs(get,qs): + """ + Verifica atributos do GET e retorna queryset correspondente + """ + kwargs = {} + for k,v in get.iteritems(): + if not (k == 'page' or k == 'pop' or k == 'q'): + if not k == 'o': + if k == "ot": + qs = query_ordena(qs,get["o"],get["ot"]) + else: + kwargs[str(k)] = v + qs = qs.filter(**kwargs) + return qs + + +def deleta_itens_carrinho(request): + """ + Deleta itens selecionados do carrinho + """ + if request.method == 'POST': + ids_selecionados = request.POST.getlist('_selected_action') + if request.session.has_key('carrinho_parlamentar'): + lista = request.session['carrinho_parlamentar'] + for item in ids_selecionados: + lista.remove(item) + if lista: + request.session['carrinho_parlamentar'] = lista + else: + del lista; + del request.session['carrinho_parlamentar'] + + return HttpResponseRedirect('.') + + +def labels_report(request, id=None, formato='3x9_etiqueta'): + """ TODO: adicionar suporte para resultado de pesquisa do admin. + """ + + if request.POST: + if request.POST.has_key('tipo_etiqueta'): + tipo = request.POST['tipo_etiqueta'] + if request.POST.has_key('tamanho_etiqueta'): + formato = request.POST['tamanho_etiqueta'] + + + if id: + qs = Parlamentar.objects.filter(pk=id) + else: + qs = carrinhoOrGet_for_qs(request) + + if not qs: + return HttpResponseRedirect('../') + + response = HttpResponse(mimetype='application/pdf') + response['Content-Disposition'] = 'attachment; filename=casas.pdf' + report = ParlamentaresLabels(queryset=qs, formato=formato) + report.generate_by(PDFGenerator, filename=response) + + return response \ No newline at end of file diff --git a/sigi/templates/admin/carrinho.html b/sigi/templates/admin/carrinho.html index 38ca4c7..d1850d2 100644 --- a/sigi/templates/admin/carrinho.html +++ b/sigi/templates/admin/carrinho.html @@ -60,7 +60,7 @@
- {%if not carIsEmpty%} + {% if not carIsEmpty %}
  • @@ -71,7 +71,7 @@
    {% block tabela %}{% endblock %}
    - {%if not carIsEmpty%} + {% if not carIsEmpty %}
    • diff --git a/sigi/templates/admin/parlamentares/parlamentar/change_form.html b/sigi/templates/admin/parlamentares/parlamentar/change_form.html new file mode 100644 index 0000000..b59cb99 --- /dev/null +++ b/sigi/templates/admin/parlamentares/parlamentar/change_form.html @@ -0,0 +1,14 @@ +{% extends "admin/change_form.html" %} +{% load i18n reporting_tags %} + +{% block object-tools %} +{% if change %}{% if not is_popup %} + +{% endif %}{% endif %} +{% endblock %} diff --git a/sigi/templates/admin/parlamentares/parlamentar/change_list.html b/sigi/templates/admin/parlamentares/parlamentar/change_list.html new file mode 100644 index 0000000..1798916 --- /dev/null +++ b/sigi/templates/admin/parlamentares/parlamentar/change_list.html @@ -0,0 +1,14 @@ +{% extends "admin/change_list.html" %} +{% load adminmedia admin_list i18n reporting_tags %} + +{% block object-tools %} + + +{% endblock %} \ No newline at end of file diff --git a/sigi/urls.py b/sigi/urls.py index 418e0f8..0bcc4cb 100644 --- a/sigi/urls.py +++ b/sigi/urls.py @@ -1,14 +1,17 @@ #-*- coding:utf-8 -*- +import sites + from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.views.generic.simple import redirect_to, direct_to_template -import sites + from sigi.apps.servicos.models import TipoServico from sigi.apps.contatos.models import UnidadeFederativa # register admin filters import admin.filterspecs + urlpatterns = patterns( '', @@ -30,6 +33,11 @@ urlpatterns = patterns( 'sigi.apps.casas.views.labels_report'), (r'^sigi/casas/casalegislativa/(?P\w+)/labels/', 'sigi.apps.casas.views.labels_report'), + # reports labels parlamentares + (r'^sigi/parlamentares/parlamentar/labels/', + 'sigi.apps.parlamentares.views.labels_report'), + (r'^sigi/parlamentares/parlamentar/(?P\w+)/labels/', + 'sigi.apps.parlamentares.views.labels_report'), # reports labels sem presidente (r'^sigi/casas/casalegislativa/labels_sem_presidente/', 'sigi.apps.casas.views.labels_report_sem_presidente'), @@ -58,6 +66,13 @@ urlpatterns = patterns( 'sigi.apps.casas.views.excluir_carrinho'), (r'^sigi/casas/casalegislativa/carrinho/', 'sigi.apps.casas.views.visualizar_carrinho'), + #Carrinho Parlamentar + (r'^sigi/parlamentares/parlamentar/carrinho/deleta_itens_carrinho', + 'sigi.apps.parlamentares.views.deleta_itens_carrinho'), + #(r'^sigi/parlamentares/parlamentar/carrinho/exluir_carrinho', + # 'sigi.apps.parlamentares.views.excluir_carrinho'), + (r'^sigi/parlamentares/parlamentar/carrinho', + 'sigi.apps.parlamentares.views.visualizar_carrinho'), #Carrinho Convenio (r'^sigi/convenios/convenio/carrinho/deleta_itens_carrinho', 'sigi.apps.convenios.views.deleta_itens_carrinho'),