Browse Source

Adicionando csv de serviços de acordo com o tkt #119

pull/129/head
Lude Ribeiro 3 years ago
parent
commit
44b2214910
  1. 13
      sigi/apps/casas/models.py
  2. 49
      sigi/apps/servicos/admin.py
  3. 4
      sigi/apps/servicos/templates/admin/servicos/servico/change_list.html
  4. 4
      sigi/apps/servicos/urls.py
  5. 190
      sigi/apps/servicos/views.py

13
sigi/apps/casas/models.py

@ -194,6 +194,19 @@ class Orgao(models.Model):
return self.funcionario_set.get(setor='presidente')
except Funcionario.DoesNotExist:
return None
@property
def contato_interlegis(self):
""" Link para acessar diretamente o contato do presidente da casa
Util para relatorios antigos
"""
try:
if self.funcionario_set.filter(setor='contato_interlegis').count() > 1:
return self.funcionario_set.filter(setor='contato_interlegis')[0]
else:
return self.funcionario_set.get(setor='contato_interlegis')
except Funcionario.DoesNotExist:
return None
@property
def total_parlamentares(self):

49
sigi/apps/servicos/admin.py

@ -11,6 +11,7 @@ from sigi.apps.casas.admin import FuncionariosInline, GerentesInterlegisFilter
from sigi.apps.casas.models import Orgao
from sigi.apps.servicos.models import (Servico, LogServico, CasaAtendida,
TipoServico)
from sigi.apps.servicos.views import adicionar_servicos_carrinho
from sigi.apps.utils.base_admin import BaseModelAdmin
@ -111,6 +112,7 @@ class ServicoAtivoFilter(admin.SimpleListFilter):
return queryset
class ServicoAdmin(BaseModelAdmin):
change_list_template = "servico/change_list.html"
form = ServicoFormAdmin
actions = ['calcular_data_uso', ]
list_display = ('casa_legislativa', 'get_codigo_interlegis', 'get_uf', 'tipo_servico', 'hospedagem_interlegis',
@ -137,6 +139,7 @@ class ServicoAdmin(BaseModelAdmin):
'casa_legislativa__municipio__uf',
)
list_display_links = []
actions = ['adicionar_servicos']
ordering = ('casa_legislativa__municipio__uf', 'casa_legislativa', 'tipo_servico',)
inlines = (LogServicoInline,)
search_fields = ('casa_legislativa__search_text',)
@ -169,6 +172,22 @@ class ServicoAdmin(BaseModelAdmin):
get_link_erro.short_description = _(u"Erro na atualização")
get_link_erro.admin_order_field = 'erro_atualizacao'
def adicionar_servicos(self, request, queryset):
if 'carrinho_servicos' in request.session:
q1 = len(request.session['carrinho_servicos'])
else:
q1 = 0
adicionar_servicos_carrinho(request, queryset=queryset)
q2 = len(request.session['carrinho_servicos'])
quant = q2 - q1
if quant:
self.message_user(request, str(q2 - q1) + _(u" Serviços adicionados no carrinho"))
else:
self.message_user(request, _(u"Os Serviços selecionados já foram adicionadas anteriormente"))
return HttpResponseRedirect('.')
adicionar_servicos.short_description = _(u"Armazenar serviços no carrinho para exportar")
def calcular_data_uso(self, request, queryset):
for servico in queryset:
servico.atualiza_data_uso()
@ -186,7 +205,7 @@ class ServicoAdmin(BaseModelAdmin):
def lookup_allowed(self, lookup, value):
return super(ServicoAdmin, self).lookup_allowed(lookup, value) or \
lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact']
lookup in ['casa_legislativa__municipio__uf__codigo_ibge__exact', ]
def add_view(self, request, form_url='', extra_context=None):
id_casa = request.GET.get('id_casa', None)
@ -234,6 +253,34 @@ class ServicoAdmin(BaseModelAdmin):
obj.casa_legislativa = Orgao.objects.get(pk=id_casa)
return obj
def changelist_view(self, request, extra_context=None):
from sigi.apps.convenios.views import normaliza_data
request.GET._mutable = True
normaliza_data(request.GET, 'data_ativacao__gte')
normaliza_data(request.GET, 'data_ativacao__lte')
request.GET._mutable = False
return super(ServicoAdmin, self).changelist_view(
request,
extra_context={'query_str': '?' + request.META['QUERY_STRING']}
)
def adicionar_servicos(self, request, queryset):
if 'carrinho_servicos' in request.session:
q1 = len(request.session['carrinho_servicos'])
else:
q1 = 0
adicionar_servicos_carrinho(request, queryset=queryset)
q2 = len(request.session['carrinho_servicos'])
quant = q2 - q1
if quant:
self.message_user(request, str(q2 - q1) + _(u" Convênios adicionados no carrinho"))
else:
self.message_user(request, _(u"Os Convênios selecionados já foram adicionadas anteriormente"))
return HttpResponseRedirect('.')
adicionar_servicos.short_description = _(u"Armazenar Serviços no carrinho para exportar")
class ContatosInline(FuncionariosInline):

4
sigi/apps/servicos/templates/admin/servicos/servico/change_list.html

@ -1,4 +0,0 @@
{% extends "admin/change_list.html" %}
{% block object-tools-items %}
{% endblock %}

4
sigi/apps/servicos/urls.py

@ -9,6 +9,10 @@ urlpatterns = patterns(
'sigi.apps.servicos.views',
url(r'^manifesta/$', 'casa_manifesta_view', name="casa-manifesta-view"),
url(r'^servico/carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'),
url(r'^servico/carrinho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-carrinho'), # tagerror
url(r'^servico/carrinho/deleta_itens_carrinho$', 'deleta_itens_carrinho', name='deleta-itens-carrinho'), # tagerror
url(r'^servico/csv/$', 'export_csv', name='servicos-csv'),
url(r'^munatenjson/(?P<servico>\w+)/$', 'municipios_atendidos', name="municipios-atendidos"),
url(r'^mapa/(?P<servico>\w+)/$', MapaView.as_view(), name="servicos-mapa"),
# url(r'^listacasas/(?P<sigla>\w+)', 'casas_usam_servico', name="casas-usam-servico"),

190
sigi/apps/servicos/views.py

@ -1,18 +1,24 @@
# -*- coding: utf-8 -*-
import csv
import json as simplejson # XXX trocar isso por simplesmente import json e refatorar o codigo
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import EmptyPage, InvalidPage, Paginator
from django.db.models import Q
from django.forms.forms import BoundField
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, render_to_response, get_object_or_404
from django.template.context import RequestContext
from django.utils.translation import ugettext as _
from django.views.generic.base import TemplateView
from sigi.apps.casas.models import Orgao
from sigi.apps.contatos.models import UnidadeFederativa
from sigi.apps.servicos.models import (TipoServico, CasaManifesta, CasaAtendida,
from sigi.apps.convenios.views import normaliza_data, query_ordena
from sigi.apps.servicos.models import (Servico, TipoServico, CasaManifesta, CasaAtendida,
ServicoManifesto)
@ -144,3 +150,183 @@ def casa_manifesta_view(request):
extra_context = {'uf_list': UnidadeFederativa.objects.all()}
return render_to_response('servicos/casa_manifesta.html', extra_context, context_instance=RequestContext(request))
def adicionar_servicos_carrinho(request, queryset=None, id=None):
if request.method == 'POST':
ids_selecionados = request.POST.getlist('_selected_action')
if 'carrinho_servicos' not in request.session:
request.session['carrinho_servicos'] = ids_selecionados
else:
lista = request.session['carrinho_servicos']
# Verifica se id já não está adicionado
for id in ids_selecionados:
if id not in lista:
lista.append(id)
request.session['carrinho_servicos'] = lista
def carrinhoOrGet_for_qs(request):
"""
Verifica se existe convênios na sessão se não verifica get e retorna qs correspondente.
"""
if 'carrinho_servicos' in request.session:
ids = request.session['carrinho_servicos']
qs = Servico.objects.filter(pk__in=ids)
qs = qs.order_by("casa_legislativa__municipio__uf", "casa_legislativa__municipio")
qs = get_for_qs(request.GET, qs)
else:
qs = Servico.objects.all()
if request.GET:
qs = qs.order_by("casa_legislativa__municipio__uf", "casa_legislativa__municipio")
qs = get_for_qs(request.GET, qs)
return qs
def adicionar_servicos_carrinho(request, queryset=None, id=None):
if request.method == 'POST':
ids_selecionados = request.POST.getlist('_selected_action')
if 'carrinho_servicos' not in request.session:
request.session['carrinho_servicos'] = ids_selecionados
else:
lista = request.session['carrinho_servicos']
# Verifica se id já não está adicionado
for id in ids_selecionados:
if id not in lista:
lista.append(id)
request.session['carrinho_servicos'] = lista
@login_required
def excluir_carrinho(request):
if 'carrinho_servicos' in request.session:
del request.session['carrinho_servicos']
messages.info(request, u'O carrinho foi esvaziado')
return HttpResponseRedirect('../../')
@login_required
def deleta_itens_carrinho(request):
if request.method == 'POST':
ids_selecionados = request.POST.getlist('_selected_action')
if 'carrinho_servicos' in request.session:
lista = request.session['carrinho_servicos']
for item in ids_selecionados:
lista.remove(item)
if lista:
request.session['carrinho_servicos'] = lista
else:
del lista
del request.session['carrinho_servicos']
return HttpResponseRedirect('.')
@login_required
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('carrinho_servicos' in request.session)
return render(
request,
'servicos/carrinho.html',
{
'carIsEmpty': carrinhoIsEmpty,
'paginas': paginas,
'query_str': '?' + request.META['QUERY_STRING']
}
)
def get_for_qs(get, qs):
kwargs = {}
ids = 0
get._mutable = True
normaliza_data(get, 'data_ativacao__gte')
normaliza_data(get, 'data_ativacao__lte')
get._mutable = False
for k, v in get.iteritems():
if k not in ['page', 'pop', 'q', '_popup']:
if not k == 'o':
if k == "ot":
qs = query_ordena(qs, get["o"], get["ot"])
else:
kwargs[str(k)] = v
if(str(k) == 'ids'):
ids = 1
break
qs = qs.filter(**kwargs)
if ids:
query = 'id IN (' + kwargs['ids'].__str__() + ')'
qs = Servico.objects.extra(where=[query])
return qs
@login_required
def export_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=servicos.csv'
csv_writer = csv.writer(response)
servicos = carrinhoOrGet_for_qs(request)
if not servicos:
return HttpResponseRedirect('../')
atributos = [_(u"Casa Legislativa"), _(u"Contato Interlegis"), _(u"Produto"),
_(u"Data de Ativação"), ]
if request.POST:
atributos = request.POST.getlist("itens_csv_selected")
col_titles = atributos
if _(u"Casa Legislativa") in col_titles:
pos = col_titles.index(_(u"Casa Legislativa")) + 1
col_titles.insert(pos, _(u"uf"))
pos+=1
col_titles.insert(pos, _(u"email"))
pos+=1
col_titles.insert(pos, _(u"telefone"))
if _(u"Contato Interlegis") in col_titles:
pos = col_titles.index(_(u"Contato Interlegis")) + 1
col_titles.insert(pos, _(u"Email do contato"))
csv_writer.writerow([s.encode("utf-8") for s in col_titles])
for servico in servicos:
lista = []
for atributo in atributos:
if _(u"Casa Legislativa") == atributo:
lista.append(servico.casa_legislativa.nome.encode("utf-8"))
lista.append(servico.casa_legislativa.municipio.uf.sigla.encode("utf-8"))
lista.append(servico.casa_legislativa.email)
lista.append(servico.casa_legislativa.telefone)
elif _(u"Contato Interlegis") == atributo:
lista.append(servico.casa_legislativa.contato_interlegis)
if servico.casa_legislativa.contato_interlegis is not None:
lista.append(servico.casa_legislativa.contato_interlegis.email)
else:
lista.append("")
elif _(u"Produto") == atributo:
lista.append(servico.tipo_servico.nome.encode("utf-8"))
elif _(u"Data de Ativação") == atributo:
data = ''
if servico.data_ativacao:
data = servico.data_ativacao.strftime("%d/%m/%Y")
lista.append(data.encode("utf-8"))
else:
pass
csv_writer.writerow(lista)
return response

Loading…
Cancel
Save