Browse Source

Limpeza da app Casas

revisaoSidenav
Sesostris Vieira 3 years ago
parent
commit
69b2c6fa30
  1. 133
      sigi/apps/casas/admin.py
  2. 90
      sigi/apps/casas/filters.py
  3. 179
      sigi/apps/casas/reports.py

133
sigi/apps/casas/admin.py

@ -1,9 +1,5 @@
from unicodedata import name
from urllib import response
from django.contrib import admin from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from django.contrib.contenttypes.admin import GenericTabularInline from django.contrib.contenttypes.admin import GenericTabularInline
from django.http import HttpResponseRedirect
from django.urls import reverse from django.urls import reverse
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
@ -11,17 +7,14 @@ from django_weasyprint.views import WeasyTemplateResponse
from import_export.fields import Field from import_export.fields import Field
from sigi.apps.casas.forms import OrgaoForm from sigi.apps.casas.forms import OrgaoForm
from sigi.apps.casas.models import Orgao, Presidente, Funcionario, TipoOrgao from sigi.apps.casas.models import Orgao, Presidente, Funcionario, TipoOrgao
# from sigi.apps.casas.views import report_complete, labels_report, export_csv, \
# labels_report_sem_presidente, report, \
# adicionar_casas_carrinho
from sigi.apps.casas.filters import (GerentesInterlegisFilter, ConvenioFilter, from sigi.apps.casas.filters import (GerentesInterlegisFilter, ConvenioFilter,
ExcluirConvenioFilter) ExcluirConvenioFilter, ServicoFilter)
from sigi.apps.contatos.models import Telefone from sigi.apps.contatos.models import Telefone
from sigi.apps.convenios.models import Convenio, Projeto from sigi.apps.convenios.models import Convenio
from sigi.apps.ocorrencias.models import Ocorrencia from sigi.apps.ocorrencias.models import Ocorrencia
from sigi.apps.servicos.models import Servico, TipoServico from sigi.apps.servicos.models import Servico
from sigi.apps.servicos.filters import ServicoAtivoFilter from sigi.apps.servicos.filters import ServicoAtivoFilter
from sigi.apps.utils import field_label, queryset_ascii from sigi.apps.utils import queryset_ascii
from sigi.apps.utils.mixins import CartExportReportMixin, LabeledResourse from sigi.apps.utils.mixins import CartExportReportMixin, LabeledResourse
@ -228,9 +221,9 @@ class ServicoInline(admin.TabularInline):
class OcorrenciaInline(admin.TabularInline): class OcorrenciaInline(admin.TabularInline):
model = Ocorrencia model = Ocorrencia
fields = ('data_criacao', 'assunto', 'prioridade', 'status', fields = ('data_criacao', 'assunto', 'prioridade', 'status',
'data_modificacao', 'setor_responsavel', 'link_editar',) 'data_modificacao', 'link_editar',)
readonly_fields = ('data_criacao', 'assunto', 'prioridade', 'status', readonly_fields = ('data_criacao', 'assunto', 'prioridade', 'status',
'data_modificacao', 'setor_responsavel', 'link_editar',) 'data_modificacao', 'link_editar',)
extra = 0 extra = 0
max_num = 0 max_num = 0
can_delete = False can_delete = False
@ -260,12 +253,10 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin):
list_display = ('id', 'sigla', 'nome', 'get_uf', 'get_gerentes', list_display = ('id', 'sigla', 'nome', 'get_uf', 'get_gerentes',
'get_convenios', 'get_servicos') 'get_convenios', 'get_servicos')
list_display_links = ('sigla', 'nome',) list_display_links = ('sigla', 'nome',)
# list_filter = ('tipo', ('gerentes_interlegis', GerentesInterlegisFilter),
# 'municipio__uf__nome', ConvenioFilter, ServicoAtivoFilter,
# ExcluirConvenioFilter, ServicoFilter, 'inclusao_digital',)
list_filter = ('tipo', ('gerentes_interlegis', GerentesInterlegisFilter), list_filter = ('tipo', ('gerentes_interlegis', GerentesInterlegisFilter),
'municipio__uf__nome', ConvenioFilter, ExcluirConvenioFilter, 'municipio__uf__nome', ConvenioFilter,
('servico__data_desativacao', ServicoAtivoFilter), ('servico__data_desativacao', ServicoAtivoFilter),
ExcluirConvenioFilter, ServicoFilter,
'inclusao_digital',) 'inclusao_digital',)
ordering = ('municipio__uf__nome', 'nome') ordering = ('municipio__uf__nome', 'nome')
queryset = queryset_ascii queryset = queryset_ascii
@ -318,25 +309,17 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin):
get_convenios.short_description = _('Convênios') get_convenios.short_description = _('Convênios')
def get_servicos(self, obj): def get_servicos(self, obj):
#TODO: Descomentar após migrar a app Servicos return mark_safe(
# return mark_safe( '<ul>' +
# '<ul>' + ''.join(
# ''.join( [f'<li><a href="{s.url}" target="_blank">{s}</a></li>'
# [f'<li><a href="{s.url}" target="_blank">{s}</a></li>' for s in obj.servico_set.filter(
# for s in obj.servico_set.filter( data_desativacao__isnull=True)
# data_desativacao__isnull=True) ]
# ] ) +
# ) + '</ul>'
# '</ul>'
# )
return "TODO: Descomentar após migrar a app Servicos"
get_servicos.short_description = _('Serviços')
def changelist_view(self, request, extra_context=None):
return super(OrgaoAdmin, self).changelist_view(
request,
extra_context={'query_str': '?' + request.META['QUERY_STRING']}
) )
get_servicos.short_description = _('Serviços')
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return (super(OrgaoAdmin, self).lookup_allowed(lookup, value) or return (super(OrgaoAdmin, self).lookup_allowed(lookup, value) or
@ -380,7 +363,6 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin):
'casas': self.get_queryset(request).order_by('municipio__uf','nome'), 'casas': self.get_queryset(request).order_by('municipio__uf','nome'),
'title': _('Relatório completo') 'title': _('Relatório completo')
} }
print (context)
return WeasyTemplateResponse( return WeasyTemplateResponse(
filename='relatorio_completo.pdf', filename='relatorio_completo.pdf',
request=request, request=request,
@ -390,85 +372,10 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin):
) )
relatorio_completo.title = _('Relatório completo') relatorio_completo.title = _('Relatório completo')
# def etiqueta_presidente_25(self, request):
# return HttpResponseRedirect('..')
# etiqueta_presidente_25.title = _('Etiqueta 2 x 5 com presidente')
# etiqueta_presidente_25.icon = 'label'
# def etiqueta_presidente_39(self, request):
# return HttpResponseRedirect('..')
# etiqueta_presidente_39.title = _('Etiqueta 3 x 9 com presidente')
# etiqueta_presidente_39.icon = 'label'
# def etiqueta_25(self, request):
# return HttpResponseRedirect('..')
# etiqueta_25.title = _('Etiqueta 2 x 5 sem presidente')
# etiqueta_25.icon = 'label'
# def etiqueta_39(self, request):
# return HttpResponseRedirect('..')
# etiqueta_39.title = _('Etiqueta 3 x 9 sem presidente')
# etiqueta_39.icon = 'label'
# def etiqueta_parlamentar_25(self, request):
# return HttpResponseRedirect('..')
# etiqueta_parlamentar_25.title = _('Etiqueta 2 x 5 parlamentares')
# etiqueta_parlamentar_25.icon = 'label'
# def etiqueta_parlamentar_39(self, request):
# return HttpResponseRedirect('..')
# etiqueta_parlamentar_39.title = _('Etiqueta 3 x 9 parlamentares')
# etiqueta_parlamentar_39.icon = 'label'
#TODO: Resolver depois - sigi-boys???
# def etiqueta(self, request, queryset):
# return labels_report(request, queryset=queryset)
# etiqueta.short_description = _("Gerar etiqueta(s) da(s) casa(s) "
# "selecionada(s)")
# def etiqueta_sem_presidente(self, request, queryset):
# return labels_report_sem_presidente(request, queryset=queryset)
# etiqueta_sem_presidente.short_description = _("Gerar etiqueta(s) sem "
# "presidente da(s) casa(s) "
# "selecionada(s)")
# def relatorio(self, request, queryset):
# return report(request, queryset=queryset)
# relatorio.short_description = _("Exportar a(s) casa(s) selecionada(s) "
# "para PDF")
# def relatorio_completo(self, request, queryset):
# return report_complete(request, queryset=queryset)
# relatorio_completo.short_description = _("Gerar relatório completo da(s) "
# "casa(s) selecionada(s)")
# def relatorio_csv(self, request, queryset):
# return export_csv(request)
# relatorio_csv.short_description = _("Exportar casa(s) selecionada(s) "
# "para CSV")
# 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
# response = adicionar_casas_carrinho(request, queryset=queryset)
# q2 = len(request.session['carrinho_casas'])
# quant = q2 - q1
# if quant:
# self.message_user(request, str(q2 - q1) + " " +
# _("Casas Legislativas adicionadas no carrinho"))
# else:
# self.message_user(request, _("As Casas Legislativas selecionadas "
# "já foram adicionadas anteriormente"))
# return HttpResponseRedirect('.')
# adicionar_casas.short_description = _("Armazenar casas no carrinho para "
# "exportar")
def get_actions(self, request): def get_actions(self, request):
actions = super(OrgaoAdmin, self).get_actions(request) actions = super(OrgaoAdmin, self).get_actions(request)
if 'delete_selected' in actions: if 'delete_selected' in actions:
del actions['delete_selected'] del actions['delete_selected']
return actions return actions
admin.site.register(TipoOrgao)

90
sigi/apps/casas/filters.py

@ -1,14 +1,16 @@
from django.contrib import admin from django.contrib import admin
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from sigi.apps.servidores.models import Servidor from sigi.apps.servidores.models import Servidor
from sigi.apps.convenios.models import Convenio, Projeto from sigi.apps.convenios.models import Projeto
from sigi.apps.servicos.models import TipoServico
class GerentesInterlegisFilter(admin.filters.RelatedFieldListFilter): class GerentesInterlegisFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(GerentesInterlegisFilter, self).__init__(*args, **kwargs) super(GerentesInterlegisFilter, self).__init__(*args, **kwargs)
gerentes = Servidor.objects.filter(casas_que_gerencia__isnull=False).order_by('nome_completo').distinct() gerentes = Servidor.objects.filter(
casas_que_gerencia__isnull=False).order_by(
'nome_completo').distinct()
self.lookup_choices = [(x.id, x) for x in gerentes] self.lookup_choices = [(x.id, x) for x in gerentes]
class ConvenioFilter(admin.SimpleListFilter): class ConvenioFilter(admin.SimpleListFilter):
@ -43,57 +45,41 @@ class ExcluirConvenioFilter(admin.SimpleListFilter):
if (self.value() is None): if (self.value() is None):
return queryset return queryset
else: else:
queryset = queryset.exclude(convenio__projeto_id=self.value()).distinct('municipio__uf__nome', 'nome') queryset = queryset.exclude(
convenio__projeto_id=self.value()).distinct(
'municipio__uf__nome', 'nome')
return queryset return queryset
# class ServicoFilter(admin.SimpleListFilter): class ServicoFilter(admin.SimpleListFilter):
# title = _("Serviço") title = _("Serviço")
# parameter_name = 'servico' parameter_name = 'servico'
# def lookups(self, request, model_admin):
# return (
# ('SS', _("Sem nenhum serviço")),
# ('CS', _("Com algum serviço")),
# ('CH', _("Com algum serviço de hospedagem")),
# ('CR', _("Apenas serviço de registro")),
# ) + tuple([(p.pk, p.nome) for p in TipoServico.objects.all()])
# def queryset(self, request, queryset):
# if self.value() is not None:
# if self.value() == 'SS':
# queryset = queryset.filter(servico=None)
# elif self.value() == 'CS':
# queryset = queryset.exclude(servico=None).filter(
# servico__data_desativacao__isnull=True)
# elif self.value() == 'CR':
# queryset = queryset.exclude(servico__tipo_servico__modo='H') \
# .exclude(servico=None)
# elif self.value() == 'CH':
# queryset = queryset.filter(
# servico__tipo_servico__modo='H',
# servico__data_desativacao__isnull=True
# )
# else:
# queryset = queryset.filter(
# servico__tipo_servico_id=self.value()
# )
# return queryset.distinct('municipio__uf__nome', 'nome') def lookups(self, request, model_admin):
return (
# class ServicoAtivoFilter(admin.SimpleListFilter): ('SS', _("Sem nenhum serviço")),
# title = _("Serviço ativo") ('CS', _("Com algum serviço")),
# parameter_name = 'ativo' ('CH', _("Com algum serviço de hospedagem")),
('CR', _("Apenas serviço de registro")),
) + tuple([(p.pk, p.nome) for p in TipoServico.objects.all()])
# def lookups(self, request, model_admin): def queryset(self, request, queryset):
# return ( if self.value() is not None:
# ('ativo', _("Ativo")), if self.value() == 'SS':
# ('desativado', _("Desativado")), queryset = queryset.filter(servico=None)
# ) elif self.value() == 'CS':
queryset = queryset.exclude(servico=None).filter(
servico__data_desativacao__isnull=True)
elif self.value() == 'CR':
queryset = queryset.exclude(servico__tipo_servico__modo='H') \
.exclude(servico=None)
elif self.value() == 'CH':
queryset = queryset.filter(
servico__tipo_servico__modo='H',
servico__data_desativacao__isnull=True
)
else:
queryset = queryset.filter(
servico__tipo_servico_id=self.value()
)
# def queryset(self, request, queryset): return queryset.distinct('municipio__uf__nome', 'nome')
# if self.value() is not None:
# if self.value() == 'ativo':
# queryset = queryset.filter(servico__data_desativacao__isnull=True)
# else:
# queryset = queryset.filter(servico__data_desativacao__isnull=False)
# return queryset

179
sigi/apps/casas/reports.py

@ -1,179 +0,0 @@
# -*- coding: utf-8 -*-
from geraldo import Report, DetailBand, Label, ObjectValue, ReportGroup, ReportBand, landscape, SubReport, BAND_WIDTH, SystemField
from geraldo.graphics import Image
from django.templatetags.static import static
from django.utils.translation import gettext as _
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from sigi.apps.relatorios.reports import ReportDefault
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
def label_text(text):
return "%s: " % text
class CasasLegislativasLabels(Report):
"""
Usage example::
>>> from geraldo.generators import PDFGenerator
>>> queryset = Orgao.objects.filter(municipio__uf__sigla='MG')
>>> report = LabelsReport(queryset)
>>> report.generate_by(PDFGenerator, filename='./inline-detail-report.pdf')
"""
formato = ''
label_margin_top = 0.6
label_margin_left = 0.2
label_margin_right = 0.2
largura_etiqueta = 6.9
altura_etiqueta = 3.25
tamanho_fonte = 6
delta = start = 0.5
def __init__(self, queryset, formato):
super(CasasLegislativasLabels, self).__init__(queryset=queryset)
self.formato = formato
self.page_size = A4
if formato == '3x9_etiqueta':
self.margin_top = 0.25 * cm
self.margin_bottom = 0.0 * cm
self.margin_left = 0.2 * cm
self.margin_right = 0.0 * cm
self.delta = 0.3
self.start = 0
self.label_margin_top = 0.35
self.label_margin_left = 0.4
self.label_margin_right = 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.label_margin_top = 0.5
self.label_margin_left = 0.5
self.label_margin_right = 0.5
calc_width = (self.largura_etiqueta - self.label_margin_left - self.label_margin_right) * cm
calc_height = lambda rows: (self.delta * rows) * cm
calc_top = lambda row: (self.label_margin_top + row * self.delta) * cm
calc_left = self.label_margin_left * cm
my_elements = [
Label(
text=label_text(_('A Sua Excelência o(a) Senhor(a)')),
top=calc_top(0), left=calc_left, width=calc_width,
),
ObjectValue(
attribute_name='presidente',
top=calc_top(1), left=calc_left, width=calc_width,
get_value=lambda instance:
unicode(instance.presidente or "").upper()
),
ObjectValue(
attribute_name='nome',
top=calc_top(2), left=calc_left, width=calc_width, height=calc_height(2),
get_value=lambda instance:
(_("Presidente da %s") % instance.nome)
),
ObjectValue(
attribute_name='logradouro',
top=calc_top(4), left=calc_left, width=calc_width, height=calc_height(2),
get_value=lambda instance:
"%s - %s - %s." % (instance.logradouro, instance.bairro, instance.municipio),
),
ObjectValue(
attribute_name='cep',
top=calc_top(8), left=calc_left, width=calc_width,
get_value=lambda instance: "%s: %s" % (_("CEP"), instance.cep)
),
]
self.band_detail = DetailBand(
width=(self.largura_etiqueta) * cm,
height=(self.altura_etiqueta) * cm,
elements=my_elements,
display_inline=True,
default_style={'fontName': 'Helvetica', 'fontSize': self.tamanho_fonte})
class CasasLegislativasLabelsSemPresidente(CasasLegislativasLabels):
def __init__(self, queryset, formato):
super(CasasLegislativasLabelsSemPresidente, self).__init__(queryset=queryset, formato=formato)
calc_width = (self.largura_etiqueta - self.label_margin_left - self.label_margin_right) * cm
calc_height = lambda rows: (self.delta * rows) * cm
calc_top = lambda row: (self.label_margin_top + row * self.delta) * cm
calc_left = self.label_margin_left * cm
my_elements = [
Label(
text=label_text(_('A Sua Excelência o(a) Senhor(a)')),
top=calc_top(0), left=calc_left, width=calc_width,
),
ObjectValue(
attribute_name='nome',
top=calc_top(1), left=calc_left, width=calc_width, height=calc_height(2),
get_value=lambda instance:
(_("Presidente da %s") % instance.nome)
),
ObjectValue(
attribute_name='logradouro',
top=calc_top(3), left=calc_left, width=calc_width, height=calc_height(2),
get_value=lambda instance:
"%s - %s - %s." % (instance.logradouro, instance.bairro, instance.municipio),
),
ObjectValue(
attribute_name='cep',
top=calc_top(8), left=calc_left, width=calc_width,
get_value=lambda instance: "%s: %s" % (_("CEP"), instance.cep)
),
]
self.band_detail = DetailBand(
width=(self.largura_etiqueta) * cm,
height=(self.altura_etiqueta) * cm,
elements=my_elements,
display_inline=True,
default_style={'fontName': 'Helvetica', 'fontSize': self.tamanho_fonte})
Loading…
Cancel
Save