Browse Source

emissão de etiquetas para parlamentares

stable/1.0
Breno Teixeira 12 years ago
parent
commit
662fc7bea8
  1. 3
      sigi/apps/casas/admin.py
  2. 2
      sigi/apps/casas/views.py
  3. 2
      sigi/apps/mesas/admin.py
  4. 4
      sigi/apps/mesas/models.py
  5. 21
      sigi/apps/parlamentares/admin.py
  6. 21
      sigi/apps/parlamentares/models.py
  7. 541
      sigi/apps/parlamentares/reports.py
  8. 78
      sigi/apps/parlamentares/templates/parlamentares/carrinho.html
  9. 14
      sigi/apps/parlamentares/templates/parlamentares/change_form.html
  10. 9
      sigi/apps/parlamentares/templates/parlamentares/change_list.html
  11. 149
      sigi/apps/parlamentares/views.py
  12. 4
      sigi/templates/admin/carrinho.html
  13. 14
      sigi/templates/admin/parlamentares/parlamentar/change_form.html
  14. 14
      sigi/templates/admin/parlamentares/parlamentar/change_list.html
  15. 17
      sigi/urls.py

3
sigi/apps/casas/admin.py

@ -123,7 +123,8 @@ class CasaLegislativaAdmin(admin.ModelAdmin):
relatorio_csv.short_description = u"Exportar casa(s) selecionada(s) para CSV" relatorio_csv.short_description = u"Exportar casa(s) selecionada(s) para CSV"
def adicionar_casas(self, request, queryset): def adicionar_casas(self, request, queryset):
if request.session.has_key('carrinho_casas'): if 'carrinho_casas' in request.session:
#if request.session.has_key('carrinho_casas'):
q1 = len(request.session['carrinho_casas']) q1 = len(request.session['carrinho_casas'])
else: else:
q1 = 0 q1 = 0

2
sigi/apps/casas/views.py

@ -2,8 +2,8 @@
from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from geraldo.generators import PDFGenerator 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 CasasLegislativasLabels
from sigi.apps.casas.reports import CasasLegislativasLabelsSemPresidente from sigi.apps.casas.reports import CasasLegislativasLabelsSemPresidente
from sigi.apps.casas.reports import CasasLegislativasReport from sigi.apps.casas.reports import CasasLegislativasReport

2
sigi/apps/mesas/admin.py

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from django.contrib import admin from django.contrib import admin
from django.http import HttpResponse 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, from sigi.apps.mesas.models import (Legislatura, Coligacao, ComposicaoColigacao,
SessaoLegislativa, MesaDiretora, Cargo, SessaoLegislativa, MesaDiretora, Cargo,
MembroMesaDiretora) MembroMesaDiretora)

4
sigi/apps/mesas/models.py

@ -1,4 +1,4 @@
# -*- coding: utf-8 -*- # coding: utf-8
from django.db import models from django.db import models
from sigi.apps.casas.models import CasaLegislativa from sigi.apps.casas.models import CasaLegislativa
@ -6,7 +6,7 @@ class Legislatura(models.Model):
casa_legislativa = models.ForeignKey(CasaLegislativa) casa_legislativa = models.ForeignKey(CasaLegislativa)
numero = models.PositiveSmallIntegerField(u'número legislatura') numero = models.PositiveSmallIntegerField(u'número legislatura')
data_inicio = models.DateField(u'início') 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') data_eleicao = models.DateField(u'data da eleição')
total_parlamentares = models.PositiveIntegerField(u"Total de parlamentares") total_parlamentares = models.PositiveIntegerField(u"Total de parlamentares")

21
sigi/apps/parlamentares/admin.py

@ -1,8 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from django.contrib import admin from django.contrib import admin
from django.contrib.contenttypes import generic from django.contrib.contenttypes import generic
from django.http import HttpResponse, HttpResponseRedirect
from sigi.apps.contatos.models import Telefone from sigi.apps.contatos.models import Telefone
from sigi.apps.parlamentares.models import Partido, Parlamentar, Mandato from sigi.apps.parlamentares.models import Partido, Parlamentar, Mandato
from sigi.apps.parlamentares.views import adicionar_parlamentar_carrinho
class MandatosInline(admin.TabularInline): class MandatosInline(admin.TabularInline):
model = Mandato model = Mandato
@ -23,6 +26,7 @@ class ParlamentarAdmin(admin.ModelAdmin):
list_display = ('nome_completo', 'nome_parlamentar', 'sexo') list_display = ('nome_completo', 'nome_parlamentar', 'sexo')
list_display_links = ('nome_completo', 'nome_parlamentar') list_display_links = ('nome_completo', 'nome_parlamentar')
list_filter = ('nome_completo', 'nome_parlamentar') list_filter = ('nome_completo', 'nome_parlamentar')
actions = ['adiciona_parlamentar',]
fieldsets = ( fieldsets = (
(None, { (None, {
'fields': ('nome_completo', 'nome_parlamentar', 'sexo'), 'fields': ('nome_completo', 'nome_parlamentar', 'sexo'),
@ -39,6 +43,23 @@ class ParlamentarAdmin(admin.ModelAdmin):
search_fields = ('nome_completo', 'nome_parlamentar', 'email', search_fields = ('nome_completo', 'nome_parlamentar', 'email',
'pagina_web',) '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): class MandatoAdmin(admin.ModelAdmin):
list_display = ('parlamentar', 'legislatura', 'partido', list_display = ('parlamentar', 'legislatura', 'partido',
'inicio_mandato', 'fim_mandato', 'is_afastado') 'inicio_mandato', 'fim_mandato', 'is_afastado')

21
sigi/apps/parlamentares/models.py

@ -12,6 +12,7 @@ class Partido(models.Model):
def __unicode__(self): def __unicode__(self):
return '%s (%s)' % (unicode(self.nome), unicode(self.sigla)) return '%s (%s)' % (unicode(self.nome), unicode(self.sigla))
class Parlamentar(models.Model): class Parlamentar(models.Model):
SEXO_CHOICES = ( SEXO_CHOICES = (
('M', 'Masculino'), ('M', 'Masculino'),
@ -38,10 +39,9 @@ class Parlamentar(models.Model):
null=True, null=True,
) )
email = models.EmailField('e-mail', blank=True) email = models.EmailField('e-mail', blank=True)
pagina_web = models.URLField( pagina_web = models.URLField(u'página web',
u'página web', blank=True, blank=True,
verify_exists=False verify_exists=False)
)
class Meta: class Meta:
ordering = ('nome_completo',) ordering = ('nome_completo',)
@ -53,19 +53,6 @@ class Parlamentar(models.Model):
return self.nome_completo 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: <em>XXXXX-XXX</em>."
# )
# telefones = generic.GenericRelation('contatos.Telefone')
class Mandato(models.Model): class Mandato(models.Model):
SUPLENCIA_CHOICES = ( SUPLENCIA_CHOICES = (
('T', 'Titular'), ('T', 'Titular'),

541
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 "<<PARLAMENTAR SEM MANDATO - impossivel definir endereço>>"
def bairro_parlamentar(instance):
try:
return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.bairro
except:
return "<<PARLAMENTAR SEM MANDATO - impossivel definir endereço>>"
def municipio_parlamentar(instance):
try:
return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.municipio
except:
return "<<PARLAMENTAR SEM MANDATO - impossivel definir endereço>>"
def cep_parlamentar(instance):
try:
return instance.mandato_set.latest('inicio_mandato').legislatura.casa_legislativa.cep
except:
return "<<PARLAMENTAR SEM MANDATO - impossivel definir endereço>>"
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},
),
)
]

78
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 %}<h1>Parlamentares no Carrinho</h1>{% endblock %}
{% block mensagem%}
<ul class="messagelist">
{%if carIsEmpty%}
<li class="warning">O carrinho está vazio, sendo assim todas as casas entram na lista para exportação de acordo com os filtros aplicados.</li>
{%else%}
<li>{{paginas.paginator.count}}Parlamentares no carrinho.</li>
{%endif%}
</ul>
{% endblock %}
{% block action %}deleta_itens_carrinho{% endblock %}
{% block tabela %}
<table>
<thead>
<tr>
{%if not carIsEmpty%}
<th class="sorted ascending"><!-- <input type="checkbox" id="action-toggle" style="display: inline;">-->
</th>
{% endif %}
<th class="sorted ascending">Nome</th>
<th class="sorted ascending">Nome parlamentar</th>
<th class="sorted ascending">Sexo</th>
</tr>
</thead>
<tbody>
{% for parlamentar in paginas.object_list %}
<tr class="{% cycle 'row1' 'row2' %}">
{%if not carIsEmpty%}
<th><input type="checkbox" name="_selected_action"
value="{{parlamentar.id}}" class="action-select" /></th>
{% endif %}
<td style="text-align: left;">{{parlamentar.nome_completo}}</td>
<td>{{parlamentar.nome_parlamentar}}</td>
<td>{{parlamentar.get_sexo_display}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
{% block botoes %}
<div id="tabs">
<ul>
<li><a href="#tabs-1">Etiqueta</a></li>
</ul>
<div id="tabs-1">
<form action="../labels/{{query_str}}" method="post">{% csrf_token %}
<fieldset><legend>Formato da Etiqueta</legend>
<ul class="formato_etiqueta">
<li><input type="radio" name="tamanho_etiqueta"
value="2x5_etiqueta"><label>2x5</label></li>
<li><input type="radio" name="tamanho_etiqueta"
value="3x9_etiqueta" checked="checked"><label>3x9</label></li>
</ul>
</fieldset>
<ul class="botoes">
<li><input type="submit" value="Gerar Etiqueta" /></li>
</ul>
</form>
</div>
{% endblock %}

14
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 %}
<ul class="object-tools">
<li><a href="report_complete/">Relatório</a></li>
<li><a href="labels/">Etiqueta</a></li>
<li><a href="labels_sem_presidente/">Etiqueta sem presidente</a></li>
<li><a href="history/" class="historylink">{% trans "History" %}</a></li>
{% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif%}
</ul>
{% endif %}{% endif %}
{% endblock %}

9
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 %}
<ul class="object-tools">
<li><a href="#">Casas sem Processo de Convênio</a></li>
</ul>
{% endblock %}

149
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

4
sigi/templates/admin/carrinho.html

@ -60,7 +60,7 @@
<div id="changelist" class="module"> <div id="changelist" class="module">
<form action="{% block action %}#{% endblock %}" <form action="{% block action %}#{% endblock %}"
class="changelist-form" method="post"> class="changelist-form" method="post">
{%if not carIsEmpty%} {% if not carIsEmpty %}
<div class="botoes"> <div class="botoes">
<ul class="botao_excluir"> <ul class="botao_excluir">
<li><input class="botao_excluir" type="submit" value=" Excluir do carrinho os itens selecionados" /></li> <li><input class="botao_excluir" type="submit" value=" Excluir do carrinho os itens selecionados" /></li>
@ -71,7 +71,7 @@
<div class="result_list"> <div class="result_list">
{% block tabela %}{% endblock %} {% block tabela %}{% endblock %}
</div> </div>
{%if not carIsEmpty%} {% if not carIsEmpty %}
<div class="botoes"> <div class="botoes">
<ul class="botao_excluir"> <ul class="botao_excluir">
<li><input class="botao_excluir" type="submit" value=" Excluir do carrinho os itens selecionados" /></li> <li><input class="botao_excluir" type="submit" value=" Excluir do carrinho os itens selecionados" /></li>

14
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 %}
<ul class="object-tools">
<li><a href="report_complete/">Relatório</a></li>
<li><a href="labels/">Etiqueta</a></li>
<li><a href="labels_sem_presidente/">Etiqueta sem presidente</a></li>
<li><a href="history/" class="historylink">{% trans "History" %}</a></li>
{% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif%}
</ul>
{% endif %}{% endif %}
{% endblock %}

14
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 %}
<ul class="object-tools">
<li><a onclick="return showRelatedObjectLookupPopup(this);" href="carrinho/{{query_str}}">Carrinho / Exportar</a></li>
<li>
<a href="add/{% if is_popup %}?_popup=1{% endif %}" class="addlink">
{% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
</a>
</li>
</ul>
{% endblock %}

17
sigi/urls.py

@ -1,14 +1,17 @@
#-*- coding:utf-8 -*- #-*- coding:utf-8 -*-
import sites
from django.conf import settings from django.conf import settings
from django.conf.urls.defaults import patterns, include, url from django.conf.urls.defaults import patterns, include, url
from django.views.generic.simple import redirect_to, direct_to_template from django.views.generic.simple import redirect_to, direct_to_template
import sites
from sigi.apps.servicos.models import TipoServico from sigi.apps.servicos.models import TipoServico
from sigi.apps.contatos.models import UnidadeFederativa from sigi.apps.contatos.models import UnidadeFederativa
# register admin filters # register admin filters
import admin.filterspecs import admin.filterspecs
urlpatterns = patterns( urlpatterns = patterns(
'', '',
@ -30,6 +33,11 @@ urlpatterns = patterns(
'sigi.apps.casas.views.labels_report'), 'sigi.apps.casas.views.labels_report'),
(r'^sigi/casas/casalegislativa/(?P<id>\w+)/labels/', (r'^sigi/casas/casalegislativa/(?P<id>\w+)/labels/',
'sigi.apps.casas.views.labels_report'), '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<id>\w+)/labels/',
'sigi.apps.parlamentares.views.labels_report'),
# reports labels sem presidente # reports labels sem presidente
(r'^sigi/casas/casalegislativa/labels_sem_presidente/', (r'^sigi/casas/casalegislativa/labels_sem_presidente/',
'sigi.apps.casas.views.labels_report_sem_presidente'), 'sigi.apps.casas.views.labels_report_sem_presidente'),
@ -58,6 +66,13 @@ urlpatterns = patterns(
'sigi.apps.casas.views.excluir_carrinho'), 'sigi.apps.casas.views.excluir_carrinho'),
(r'^sigi/casas/casalegislativa/carrinho/', (r'^sigi/casas/casalegislativa/carrinho/',
'sigi.apps.casas.views.visualizar_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 #Carrinho Convenio
(r'^sigi/convenios/convenio/carrinho/deleta_itens_carrinho', (r'^sigi/convenios/convenio/carrinho/deleta_itens_carrinho',
'sigi.apps.convenios.views.deleta_itens_carrinho'), 'sigi.apps.convenios.views.deleta_itens_carrinho'),

Loading…
Cancel
Save