From 45d8245f9106eaf5821421cf5a367676e4a6226e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Thu, 10 Feb 2022 11:17:58 -0300 Subject: [PATCH 1/9] =?UTF-8?q?Corre=C3=A7=C3=A3o=20de=20bug=20no=20Labele?= =?UTF-8?q?dResource?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/utils/mixins.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sigi/apps/utils/mixins.py b/sigi/apps/utils/mixins.py index cf80194..bb60de1 100644 --- a/sigi/apps/utils/mixins.py +++ b/sigi/apps/utils/mixins.py @@ -16,6 +16,7 @@ from import_export.admin import ExportMixin from import_export.forms import ExportForm from import_export.signals import post_export from sigi.apps.utils import field_label + class ExportFormFields(ExportForm): def __init__(self, formats, field_list, *args, **kwargs): super().__init__(formats, *args, **kwargs) @@ -42,7 +43,8 @@ class LabeledResourse(resources.ModelResource): def get_export_fields(self): fields = self.get_fields() if self.selected_fields: - fields = [f for f in fields if f.column_name in self.selected_fields] + fields = [f for f in fields + if self.get_field_name(f) in self.selected_fields] return fields def export(self, queryset=None, selected_fields=None, *args, **kwargs): @@ -51,7 +53,6 @@ class LabeledResourse(resources.ModelResource): class CartExportMixin(ExportMixin): to_encoding = 'utf-8' - actions = ['add_to_cart'] change_list_template = 'admin/cart/change_list_cart_export.html' _cart_session_name = None _cart_viewing_name = None @@ -73,6 +74,9 @@ class CartExportMixin(ExportMixin): action = self.get_action('remove_from_cart') return OrderedDict([(action[1], action)]) else: + if self.actions is None: + self.actions = [] + self.actions.append('add_to_cart') return super(CartExportMixin, self).get_actions(request) @csrf_protect_m From dcebe1ca9531d17c820781e5fb0b65fc442cbe1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Thu, 10 Feb 2022 11:34:36 -0300 Subject: [PATCH 2/9] =?UTF-8?q?App=20servi=C3=A7os=20com=20exporta=C3=A7?= =?UTF-8?q?=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/servicos/admin.py | 30 ++++++++++++++--- .../servicos/casaatendida/change_list.html | 23 ------------- .../templates/servico/change_list.html | 33 ------------------- 3 files changed, 26 insertions(+), 60 deletions(-) delete mode 100644 sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html delete mode 100644 sigi/apps/servicos/templates/servico/change_list.html diff --git a/sigi/apps/servicos/admin.py b/sigi/apps/servicos/admin.py index 812726c..27fe9cb 100644 --- a/sigi/apps/servicos/admin.py +++ b/sigi/apps/servicos/admin.py @@ -1,4 +1,5 @@ from datetime import date, timedelta +import resource from django.contrib import admin from django.urls import reverse from django.utils.encoding import force_str @@ -6,11 +7,33 @@ from django.utils.safestring import mark_safe from django.forms.models import ModelForm from django.http import Http404, HttpResponseRedirect from django.utils.translation import gettext as _ - +from import_export.fields import Field 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.utils.mixins import CartExportMixin, LabeledResourse + +class ServicoExportResourse(LabeledResourse): + telefone_casa = Field(column_name='Casa Legislativa/telefone') + hospedagem_interlegis = Field(column_name='hospedagem no interlegis') + class Meta: + model = Servico + fields = ('casa_legislativa__nome', 'casa_legislativa__municipio__nome', + 'casa_legislativa__municipio__uf__sigla', + 'casa_legislativa__email', 'telefone_casa', + 'contato_tecnico__nome', 'contato_tecnico__email', + 'contato_tecnico__nota', 'tipo_servico__nome', 'url', + 'hospedagem_interlegis', 'data_ativacao', 'data_desativacao', + 'motivo_desativacao', 'data_ultimo_uso', 'erro_atualizacao') + export_order = fields + def dehydrate_telefone_casa(self, servico): + return servico.casa_legislativa.telefone + def dehydrate_hospedagem_interlegis(self, servico): + if servico.hospedagem_interlegis: + return _("Sim") + else: + return _("Não") class LogServicoInline(admin.StackedInline): @@ -110,8 +133,7 @@ class ServicoAtivoFilter(admin.SimpleListFilter): return queryset @admin.register(Servico) -class ServicoAdmin(admin.ModelAdmin): - change_list_template = "servico/change_list.html" +class ServicoAdmin(CartExportMixin, admin.ModelAdmin): form = ServicoFormAdmin actions = ['calcular_data_uso', ] list_display = ('casa_legislativa', 'get_codigo_interlegis', 'get_uf', @@ -142,11 +164,11 @@ class ServicoAdmin(admin.ModelAdmin): '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',) + resource_class = ServicoExportResourse def get_codigo_interlegis(self, obj): return obj.casa_legislativa.codigo_interlegis diff --git a/sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html b/sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html deleted file mode 100644 index 104fd94..0000000 --- a/sigi/apps/servicos/templates/admin/servicos/casaatendida/change_list.html +++ /dev/null @@ -1,23 +0,0 @@ -{% extends "admin/change_list.html" %} -{% load admin_list i18n admin_urls %} - -{% block extrahead %} -{{ block.super }} - -{% endblock %} - -{% block object-tools-items %} -
  • - - {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %} -
  • - {{ block.super }} -{% endblock %} diff --git a/sigi/apps/servicos/templates/servico/change_list.html b/sigi/apps/servicos/templates/servico/change_list.html deleted file mode 100644 index cc44655..0000000 --- a/sigi/apps/servicos/templates/servico/change_list.html +++ /dev/null @@ -1,33 +0,0 @@ -{% extends "change_list_with_cart.html" %} -{% load i18n %} - - -{% block extra_search %} - -{% endblock %} \ No newline at end of file From 2f2b9345afdd9c2a156071394da86994cd08cd9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 11 Feb 2022 21:32:32 -0300 Subject: [PATCH 3/9] =?UTF-8?q?Cria=C3=A7=C3=A3o=20do=20DateRangeFilter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/utils/filters.py | 42 ++++++++++++++++++- .../templates/admin/date_range_filter.html | 13 ++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 sigi/apps/utils/templates/admin/date_range_filter.html diff --git a/sigi/apps/utils/filters.py b/sigi/apps/utils/filters.py index faf0c7f..1b1034b 100644 --- a/sigi/apps/utils/filters.py +++ b/sigi/apps/utils/filters.py @@ -1,5 +1,6 @@ import string from math import log10 +from django import forms from django.contrib import admin from django.contrib.admin.options import IncorrectLookupParameters from django.utils.translation import ngettext, gettext as _ @@ -132,4 +133,43 @@ class RangeFilter(admin.FieldListFilter): except (ValueError, ValidationError) as e: raise IncorrectLookupParameters(e) - return queryset \ No newline at end of file + return queryset + +class DateRangeFilter(admin.FieldListFilter): + template = 'admin/date_range_filter.html' + def __init__(self, field, request, params, model, model_admin, field_path): + self.model = model + self.model_admin = model_admin + self.lookup_kwargs = [f'{field_path}__gte', f'{field_path}__lte'] + + super().__init__(field, request, params, model, model_admin, field_path) + + form = self.get_date_form(self.used_parameters) + if form.is_valid(): + self.used_parameters = { + key: value for key,value in form.cleaned_data.items() + if value is not None + } + else: + self.used_parameters = {} + + def has_output(self): + return self.model.objects.exists() + + def expected_parameters(self): + return self.lookup_kwargs + + def choices(self, changelist): + return [{ + 'query_string': changelist.get_query_string( + remove=self.lookup_kwargs), + 'form': self.get_date_form(self.used_parameters) + }] + + def get_date_form(self, context={}): + date_fields = {name: forms.DateField(required=False) + for name in self.lookup_kwargs} + DateForm = type('DateForm', (forms.Form,), date_fields) + + return DateForm(context) + diff --git a/sigi/apps/utils/templates/admin/date_range_filter.html b/sigi/apps/utils/templates/admin/date_range_filter.html new file mode 100644 index 0000000..c3ee1ec --- /dev/null +++ b/sigi/apps/utils/templates/admin/date_range_filter.html @@ -0,0 +1,13 @@ +{% load i18n %} +{% with choice=choices.0 %} +
    +
    + + + {% trans 'All' %} + {% for field in choice.form %} + + {% endfor %} +
    +
    +{% endwith %} \ No newline at end of file From cbda826d2a9d184b124f9e4a645e7dd9858efb37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 11 Feb 2022 21:35:32 -0300 Subject: [PATCH 4/9] =?UTF-8?q?Filtro=20por=20servi=C3=A7o=20ativo,=20reor?= =?UTF-8?q?ganiza=C3=A7=C3=A3o=20do=20admin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/servicos/admin.py | 148 ++++------------------------------ sigi/apps/servicos/filters.py | 96 ++++++++++++++++++++++ sigi/apps/servicos/forms.py | 30 +++++++ 3 files changed, 142 insertions(+), 132 deletions(-) create mode 100644 sigi/apps/servicos/filters.py create mode 100644 sigi/apps/servicos/forms.py diff --git a/sigi/apps/servicos/admin.py b/sigi/apps/servicos/admin.py index 27fe9cb..fb11eb0 100644 --- a/sigi/apps/servicos/admin.py +++ b/sigi/apps/servicos/admin.py @@ -1,10 +1,7 @@ -from datetime import date, timedelta -import resource from django.contrib import admin from django.urls import reverse from django.utils.encoding import force_str from django.utils.safestring import mark_safe -from django.forms.models import ModelForm from django.http import Http404, HttpResponseRedirect from django.utils.translation import gettext as _ from import_export.fields import Field @@ -12,6 +9,9 @@ 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.filters import ServicoAtivoFilter, DataUtimoUsoFilter +from sigi.apps.servicos.forms import ServicoFormAdmin +from sigi.apps.utils.filters import DateRangeFilter from sigi.apps.utils.mixins import CartExportMixin, LabeledResourse class ServicoExportResourse(LabeledResourse): @@ -35,103 +35,29 @@ class ServicoExportResourse(LabeledResourse): else: return _("Não") - class LogServicoInline(admin.StackedInline): model = LogServico Fieldset = ((None, {'fields': (('data', 'descricao'), 'log')})) extra = 1 -class ServicoFormAdmin(ModelForm): - class Meta: - model = Servico - fields = '__all__' - - def __init__(self, *args, **kwargs): - super(ServicoFormAdmin, self).__init__(*args, **kwargs) - - self.fields['contato_tecnico'].choices = () - self.fields['contato_administrativo'].choices = () - - if self.instance.casa_legislativa_id: - id_casa = self.instance.casa_legislativa_id - elif 'initial' in kwargs and 'id_casa' in kwargs['initial']: - id_casa = kwargs['initial']['id_casa'] - self.instance.casa_legislativa_id = id_casa - else: - id_casa = None +class ContatosInline(FuncionariosInline): + can_delete = False # Equipe do SEIT não pode excluir pessoas de contato + # SEIT see all contacts, including President + def get_queryset(self, request): + return self.model.objects.all() - if id_casa: - casa = CasaAtendida.objects.get(pk=id_casa) - contatos = [ - (f.id, force_str(f)) for f in casa.funcionario_set.all() - ] - self.fields['contato_tecnico'].choices = contatos - self.fields['contato_administrativo'].choices = contatos + def get_queryset(self, request): + return (self.model.objects.exclude(desativado=True) + .extra(select={'ult_null': 'ult_alteracao is null'}) + .order_by('ult_null', '-ult_alteracao') + # A função extra foi usada para quando existir um registro com o campo igual a null não aparecer na frente dos mais novos + ) @admin.register(TipoServico) class TipoServicoAdmin(admin.ModelAdmin): list_display = ('id', 'sigla', 'nome', 'qtde_casas_atendidas', ) ordering = ['id'] -class DataUtimoUsoFilter(admin.SimpleListFilter): - title = _("Atualização") - parameter_name = 'atualizacao' - - def lookups(self, request, model_admin): - return ( - ('err', _("Erro na verificação")), - ('year', _("Sem atualização há um ano ou mais")), - ('semester', _("Sem atualização de seis meses a um ano")), - ('quarter', _("Sem atualização de três a seis meses")), - ('month', _("Sem atualização de um a três meses")), - ('week', _("Sem atualização de uma semana a um mês")), - ('updated', _("Atualizado na última semana")), - ) - - def queryset(self, request, queryset): - if self.value() is not None: - queryset = queryset.exclude(tipo_servico__string_pesquisa="") - if self.value() == 'err': - queryset = queryset.exclude(erro_atualizacao="") - elif self.value() == 'year': - limite = date.today() - timedelta(days=365) - queryset = queryset.filter(data_ultimo_uso__lte=limite) - else: - de = date.today() - ( - timedelta(days=365) if self.value() == 'semester' else - timedelta(days=6*30) if self.value() == 'quarter' else - timedelta(days=3*30) if self.value() == 'month' else - timedelta(days=30) if self.value() == 'week' else - timedelta(days=0) - ) - ate = date.today() - ( - timedelta(days=6*30) if self.value() == 'semester' else - timedelta(days=3*30) if self.value() == 'quarter' else - timedelta(days=30) if self.value() == 'month' else - timedelta(days=7) if self.value() == 'week' else - timedelta(days=0) - ) - queryset = queryset.filter(data_ultimo_uso__range=(de, ate)) - return queryset - -class ServicoAtivoFilter(admin.SimpleListFilter): - title = _("Serviço ativo") - parameter_name = 'ativo' - - def lookups(self, request, model_admin): - return ( - ('ativo', _("Ativo")), - ('desativado', _("Desativado")), - ) - - def queryset(self, request, queryset): - if self.value() is not None: - if self.value() == 'ativo': - queryset = queryset.filter(data_desativacao__isnull=True) - else: - queryset = queryset.filter(data_desativacao__isnull=False) - return queryset - @admin.register(Servico) class ServicoAdmin(CartExportMixin, admin.ModelAdmin): form = ServicoFormAdmin @@ -158,7 +84,8 @@ class ServicoAdmin(CartExportMixin, admin.ModelAdmin): list_filter = ( 'tipo_servico', 'hospedagem_interlegis', - ServicoAtivoFilter, + ('data_ativacao', DateRangeFilter), + ('data_desativacao', ServicoAtivoFilter), DataUtimoUsoFilter, ('casa_legislativa__gerentes_interlegis', GerentesInterlegisFilter), 'casa_legislativa__municipio__uf', @@ -200,21 +127,6 @@ class ServicoAdmin(CartExportMixin, admin.ModelAdmin): get_link_erro.short_description = _("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) + _(" Serviços adicionados no carrinho")) - # else: - # self.message_user(request, _("Os Serviços selecionados já foram adicionadas anteriormente")) - # return HttpResponseRedirect('.') - # adicionar_servicos.short_description = _("Armazenar serviços no carrinho para exportar") - def calcular_data_uso(self, request, queryset): for servico in queryset: servico.atualiza_data_uso() @@ -289,34 +201,6 @@ class ServicoAdmin(CartExportMixin, admin.ModelAdmin): 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) + _(" Convênios adicionados no carrinho")) - # else: - # self.message_user(request, _("Os Convênios selecionados já foram adicionadas anteriormente")) - # return HttpResponseRedirect('.') - # adicionar_servicos.short_description = _("Armazenar Serviços no carrinho para exportar") - -class ContatosInline(FuncionariosInline): - can_delete = False # Equipe do SEIT não pode excluir pessoas de contato - # SEIT see all contacts, including President - def get_queryset(self, request): - return self.model.objects.all() - - def get_queryset(self, request): - return (self.model.objects.exclude(desativado=True) - .extra(select={'ult_null': 'ult_alteracao is null'}) - .order_by('ult_null', '-ult_alteracao') - # A função extra foi usada para quando existir um registro com o campo igual a null não aparecer na frente dos mais novos - ) - @admin.register(CasaAtendida) class CasaAtendidaAdmin(admin.ModelAdmin): actions = None diff --git a/sigi/apps/servicos/filters.py b/sigi/apps/servicos/filters.py new file mode 100644 index 0000000..ba432b1 --- /dev/null +++ b/sigi/apps/servicos/filters.py @@ -0,0 +1,96 @@ +from datetime import date, timedelta +from django.utils.translation import gettext as _ +from django.contrib import admin + +class ServicoAtivoFilter(admin.FieldListFilter): + parameter_name = None + + def __init__(self, field, request, params, model, model_admin, field_path): + self.model = model + self.model_admin = model_admin + self.parameter_name = f'{field_path}__isnull' + + super().__init__(field, request, params, model, model_admin, field_path) + + self.title = _("Serviço ativo") + + if self.parameter_name in params: + value = params.pop(self.parameter_name) + self.used_parameters[self.parameter_name] = value + lookup_choices = self.lookups(request, model_admin) + + if lookup_choices is None: + lookup_choices = () + self.lookup_choices = list(lookup_choices) + + def lookups(self, request, model_admin): + return ( + ('True', _('Ativo')), + ('False', _('Inativo')) + ) + + def has_output(self): + return self.model.objects.exists() + + def value(self): + return self.used_parameters.get(self.parameter_name) + + def expected_parameters(self): + return [self.parameter_name,] + + def choices(self, changelist): + yield { + 'selected': self.value() is None, + 'query_string': changelist.get_query_string( + remove=[self.parameter_name]), + 'display': _('All'), + } + for lookup, title in self.lookup_choices: + yield { + 'selected': str(self.value()) == str(lookup), + 'query_string': changelist.get_query_string( + {self.parameter_name: lookup} + ), + 'display': title, + } + +class DataUtimoUsoFilter(admin.SimpleListFilter): + title = _("Atualização") + parameter_name = 'atualizacao' + + def lookups(self, request, model_admin): + return ( + ('err', _("Erro na verificação")), + ('year', _("Sem atualização há um ano ou mais")), + ('semester', _("Sem atualização de seis meses a um ano")), + ('quarter', _("Sem atualização de três a seis meses")), + ('month', _("Sem atualização de um a três meses")), + ('week', _("Sem atualização de uma semana a um mês")), + ('updated', _("Atualizado na última semana")), + ) + + def queryset(self, request, queryset): + if self.value() is not None: + queryset = queryset.exclude(tipo_servico__string_pesquisa="") + if self.value() == 'err': + queryset = queryset.exclude(erro_atualizacao="") + elif self.value() == 'year': + limite = date.today() - timedelta(days=365) + queryset = queryset.filter(data_ultimo_uso__lte=limite) + else: + de = date.today() - ( + timedelta(days=365) if self.value() == 'semester' else + timedelta(days=6*30) if self.value() == 'quarter' else + timedelta(days=3*30) if self.value() == 'month' else + timedelta(days=30) if self.value() == 'week' else + timedelta(days=0) + ) + ate = date.today() - ( + timedelta(days=6*30) if self.value() == 'semester' else + timedelta(days=3*30) if self.value() == 'quarter' else + timedelta(days=30) if self.value() == 'month' else + timedelta(days=7) if self.value() == 'week' else + timedelta(days=0) + ) + queryset = queryset.filter(data_ultimo_uso__range=(de, ate)) + return queryset diff --git a/sigi/apps/servicos/forms.py b/sigi/apps/servicos/forms.py new file mode 100644 index 0000000..c584451 --- /dev/null +++ b/sigi/apps/servicos/forms.py @@ -0,0 +1,30 @@ +from django.forms.models import ModelForm +from django.utils.encoding import force_str +from sigi.apps.servicos.models import Servico, CasaAtendida + +class ServicoFormAdmin(ModelForm): + class Meta: + model = Servico + fields = '__all__' + + def __init__(self, *args, **kwargs): + super(ServicoFormAdmin, self).__init__(*args, **kwargs) + + self.fields['contato_tecnico'].choices = () + self.fields['contato_administrativo'].choices = () + + if self.instance.casa_legislativa_id: + id_casa = self.instance.casa_legislativa_id + elif 'initial' in kwargs and 'id_casa' in kwargs['initial']: + id_casa = kwargs['initial']['id_casa'] + self.instance.casa_legislativa_id = id_casa + else: + id_casa = None + + if id_casa: + casa = CasaAtendida.objects.get(pk=id_casa) + contatos = [ + (f.id, force_str(f)) for f in casa.funcionario_set.all() + ] + self.fields['contato_tecnico'].choices = contatos + self.fields['contato_administrativo'].choices = contatos From 14edb0b1a6414e3a586d709122c735f8ee74a6c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 11 Feb 2022 21:36:36 -0300 Subject: [PATCH 5/9] =?UTF-8?q?Casas=20com=20DateRangeFilter=20e=20melhor?= =?UTF-8?q?=20organiza=C3=A7=C3=A3o=20do=20admin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/casas/admin.py | 155 ++++++++--------- sigi/apps/casas/models.py | 8 +- .../templates/admin/casas/change_form.html | 1 - .../admin/casas/convenios_inline.html | 164 ------------------ .../admin/casas/ocorrencia_inline.html | 164 ------------------ 5 files changed, 74 insertions(+), 418 deletions(-) delete mode 100644 sigi/apps/casas/templates/admin/casas/change_form.html delete mode 100644 sigi/apps/casas/templates/admin/casas/convenios_inline.html delete mode 100644 sigi/apps/casas/templates/admin/casas/ocorrencia_inline.html diff --git a/sigi/apps/casas/admin.py b/sigi/apps/casas/admin.py index 47313fc..0de2cd7 100644 --- a/sigi/apps/casas/admin.py +++ b/sigi/apps/casas/admin.py @@ -18,8 +18,9 @@ from sigi.apps.casas.filters import (GerentesInterlegisFilter, ConvenioFilter, ExcluirConvenioFilter) from sigi.apps.contatos.models import Telefone from sigi.apps.convenios.models import Convenio, Projeto -# from sigi.apps.ocorrencias.models import Ocorrencia -# from sigi.apps.servicos.models import Servico, TipoServico +from sigi.apps.ocorrencias.models import Ocorrencia +from sigi.apps.servicos.models import Servico, TipoServico +from sigi.apps.servicos.filters import ServicoAtivoFilter from sigi.apps.utils import field_label, queryset_ascii from sigi.apps.utils.mixins import CartExportReportMixin, LabeledResourse @@ -143,10 +144,9 @@ class ConveniosInline(admin.TabularInline): 'data_retorno_sem_assinatura', 'get_anexos'] extra = 0 can_delete = False - template = 'admin/casas/convenios_inline.html' ordering = ('-data_retorno_assinatura',) - def has_add_permission(self, request): + def has_add_permission(self, request, obj): return False def get_anexos(self, obj): @@ -176,16 +176,11 @@ class ConveniosInline(admin.TabularInline): def link_convenio(self, obj): if obj.pk is None: return "" - url = reverse( - f'admin:{obj._meta.app_label}_{obj._meta.module_name}_change', - args=[obj.pk] - ) + '?_popup=1' + opts = self.opts + url = reverse(f"admin:{opts.app_label}_{opts.model_name}_change", + args=[obj.pk]) return mark_safe( - f'' - f'' - f'{_("Editar")}' + f'edit' ) link_convenio.short_description = _('Editar convenio') @@ -195,72 +190,64 @@ class ConveniosInline(admin.TabularInline): return mark_safe(obj.get_sigad_url()) link_sigad.short_description = _("Processo no Senado") -# class ServicoInline(admin.TabularInline): -# model = Servico -# fields = ('link_url', 'contato_tecnico', 'contato_administrativo', -# 'hospedagem_interlegis', 'data_ativacao', 'data_alteracao', -# 'data_desativacao', 'link_servico') -# readonly_fields = ['link_url', 'contato_tecnico', 'contato_administrativo', -# 'hospedagem_interlegis', 'data_ativacao', -# 'data_alteracao', 'data_desativacao', 'link_servico'] -# extra = 0 -# max_num = 0 -# can_delete = False -# ordering = ('-data_alteracao',) - -# def link_url(self, servico): -# if servico.data_desativacao is not None: -# return servico.url -# return mark_safe( -# f'{servico.url}' -# ) -# link_url.short_description = _('URL do serviço') - -# def link_servico(self, obj): -# if obj.pk is None: -# return "" -# url = reverse( -# f'admin:{obj._meta.app_label}_{obj._meta.module_name_change}', -# args=[obj.pk] -# ) + '?_popup=1' -# return mark_safe( -# f'' -# f'Editar' -# ) -# link_servico.short_description = _('Editar Serviço') - -# def has_add_permission(self, request): -# return False - -# class OcorrenciaInline(admin.TabularInline): -# model = Ocorrencia -# fields = ('data_criacao', 'assunto', 'prioridade', 'status', -# 'data_modificacao', 'setor_responsavel', 'link_editar',) -# readonly_fields = ('data_criacao', 'assunto', 'prioridade', 'status', -# 'data_modificacao', 'setor_responsavel', 'link_editar',) -# extra = 0 -# max_num = 0 -# can_delete = False -# template = 'admin/casas/ocorrencia_inline.html' -# ordering = ('-data_modificacao',) - -# def link_editar(self, obj): -# if obj.pk is None: -# return "" -# url = reverse( -# f'admin:{obj._meta.app_label}_{obj._meta.module_name}_change', -# args=[obj.pk] -# ) -# return mark_safe( -# f'' -# f'' -# f'{_("Editar")}' -# ) -# link_editar.short_description = _('Editar') +class ServicoInline(admin.TabularInline): + model = Servico + fields = ('link_url', 'contato_tecnico', 'contato_administrativo', + 'hospedagem_interlegis', 'data_ativacao', 'data_alteracao', + 'data_desativacao', 'link_servico') + readonly_fields = ['link_url', 'contato_tecnico', 'contato_administrativo', + 'hospedagem_interlegis', 'data_ativacao', + 'data_alteracao', 'data_desativacao', 'link_servico'] + extra = 0 + max_num = 0 + can_delete = False + ordering = ('-data_alteracao',) + + def link_url(self, servico): + if servico.data_desativacao is not None: + return servico.url + return mark_safe( + f'{servico.url}' + ) + link_url.short_description = _('URL do serviço') + + def link_servico(self, obj): + if obj.pk is None: + return "" + opts = self.opts + url = reverse(f'admin:{opts.app_label}_{opts.model_name}_change', + args=[obj.pk]) + return mark_safe( + f'edit' + ) + link_servico.short_description = _('Editar Serviço') + + def has_add_permission(self, request, obj): + return False + +class OcorrenciaInline(admin.TabularInline): + model = Ocorrencia + fields = ('data_criacao', 'assunto', 'prioridade', 'status', + 'data_modificacao', 'setor_responsavel', 'link_editar',) + readonly_fields = ('data_criacao', 'assunto', 'prioridade', 'status', + 'data_modificacao', 'setor_responsavel', 'link_editar',) + extra = 0 + max_num = 0 + can_delete = False + ordering = ('-data_modificacao',) + + def link_editar(self, obj): + if obj.pk is None: + return "" + opts = self.opts + url = reverse( + f'admin:{opts.app_label}_{opts.model_name}_change', + args=[obj.pk] + ) + return mark_safe( + f'edit' + ) + link_editar.short_description = _('Editar') @admin.register(Orgao) @@ -268,8 +255,8 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): form = OrgaoForm resource_class = OrgaoExportResourse inlines = (TelefonesInline, PresidenteInline, ContatoInterlegisInline, - FuncionariosInline, ) #ConveniosInline, ServicoInline, - # OcorrenciaInline,) + FuncionariosInline, ConveniosInline, ServicoInline, + OcorrenciaInline,) list_display = ('id', 'sigla', 'nome', 'get_uf', 'get_gerentes', 'get_convenios', 'get_servicos') list_display_links = ('sigla', 'nome',) @@ -278,6 +265,7 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): # ExcluirConvenioFilter, ServicoFilter, 'inclusao_digital',) list_filter = ('tipo', ('gerentes_interlegis', GerentesInterlegisFilter), 'municipio__uf__nome', ConvenioFilter, ExcluirConvenioFilter, + ('servico__data_desativacao', ServicoAtivoFilter), 'inclusao_digital',) ordering = ('municipio__uf__nome', 'nome') queryset = queryset_ascii @@ -295,8 +283,7 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): 'pagina_web', 'email', 'obs_pesquisa',) }), (_('Outras informações'), { - 'fields': ('observacoes', 'horario_funcionamento', 'foto', - 'recorte'), + 'fields': ('observacoes', 'horario_funcionamento', 'foto',), }), ) raw_id_fields = ('municipio',) @@ -387,7 +374,7 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): content_type='application/pdf', ) relatorio_simples.title = _('Relatório Simples') - + def relatorio_completo(self, request): context = { 'casas': self.get_queryset(request).order_by('municipio__uf','nome'), diff --git a/sigi/apps/casas/models.py b/sigi/apps/casas/models.py index ce7f461..94ef7b9 100644 --- a/sigi/apps/casas/models.py +++ b/sigi/apps/casas/models.py @@ -148,11 +148,9 @@ class Orgao(models.Model): @property def num_parlamentares(self): - # TODO: Descomentar assim que a app Parlamentares for migrada - # if not self.legislatura_set.exists(): - # return 0 - # return self.legislatura_set.latest('data_inicio').total_parlamentares - return 0 + if not self.legislatura_set.exists(): + return 0 + return self.legislatura_set.latest('data_inicio').total_parlamentares @property def telefone(self): diff --git a/sigi/apps/casas/templates/admin/casas/change_form.html b/sigi/apps/casas/templates/admin/casas/change_form.html deleted file mode 100644 index 30bf990..0000000 --- a/sigi/apps/casas/templates/admin/casas/change_form.html +++ /dev/null @@ -1 +0,0 @@ -{% extends "change_form_with_report_and_labels.html" %} diff --git a/sigi/apps/casas/templates/admin/casas/convenios_inline.html b/sigi/apps/casas/templates/admin/casas/convenios_inline.html deleted file mode 100644 index 9b9a86f..0000000 --- a/sigi/apps/casas/templates/admin/casas/convenios_inline.html +++ /dev/null @@ -1,164 +0,0 @@ -{% load i18n admin_static admin_modify bootstrapped_goodies_tags %} -
    - -
    - - diff --git a/sigi/apps/casas/templates/admin/casas/ocorrencia_inline.html b/sigi/apps/casas/templates/admin/casas/ocorrencia_inline.html deleted file mode 100644 index 2103f2a..0000000 --- a/sigi/apps/casas/templates/admin/casas/ocorrencia_inline.html +++ /dev/null @@ -1,164 +0,0 @@ -{% load i18n admin_static admin_modify bootstrapped_goodies_tags %} -
    - -
    - - From e747b4abaf94481be44f21d0e5fd074e64ceecfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 11 Feb 2022 23:06:38 -0300 Subject: [PATCH 6/9] Ajuste no menu do sistema --- sigi/apps/home/templates/menus/menu.html | 2 +- sigi/settings/menu_conf.yaml | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/sigi/apps/home/templates/menus/menu.html b/sigi/apps/home/templates/menus/menu.html index 770efd7..c96c926 100644 --- a/sigi/apps/home/templates/menus/menu.html +++ b/sigi/apps/home/templates/menus/menu.html @@ -10,7 +10,7 @@ {% for child in menu.children %} {% if child.view_name %} {% url child.view_name as item_url %} - + {{ child.title }} {% else %} diff --git a/sigi/settings/menu_conf.yaml b/sigi/settings/menu_conf.yaml index d0bc506..18f2642 100644 --- a/sigi/settings/menu_conf.yaml +++ b/sigi/settings/menu_conf.yaml @@ -37,8 +37,6 @@ main_menu: children: - title: Convênios view_name: admin:convenios_convenio_changelist - - title: Planos diretores - view_name: admin:metas_planodiretor_changelist - title: Serviços SEIT icon: cloud_done children: From c0b90f031c387bd625dc3d328eee1e5ac82e51dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Fri, 11 Feb 2022 23:08:36 -0300 Subject: [PATCH 7/9] =?UTF-8?q?Adiciona=20DateRangeFilters=20nos=20conv?= =?UTF-8?q?=C3=AAnios?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/convenios/admin.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/sigi/apps/convenios/admin.py b/sigi/apps/convenios/admin.py index 54f89f5..cc59315 100644 --- a/sigi/apps/convenios/admin.py +++ b/sigi/apps/convenios/admin.py @@ -2,7 +2,6 @@ from django.contrib import admin from django.http import HttpResponse, HttpResponseRedirect from django.utils.translation import gettext as _ from django.utils.safestring import mark_safe -from import_export.fields import Field from sigi.apps.convenios.models import (Projeto, StatusConvenio, TipoSolicitacao, Convenio, EquipamentoPrevisto, Anexo, Tramitacao, @@ -11,6 +10,7 @@ from sigi.apps.utils import queryset_ascii from sigi.apps.servidores.models import Servidor from sigi.apps.casas.admin import GerentesInterlegisFilter from sigi.apps.utils.mixins import CartExportReportMixin, LabeledResourse +from sigi.apps.utils.filters import DateRangeFilter class ConvenioExportResourse(LabeledResourse): class Meta: @@ -73,10 +73,14 @@ class ConvenioAdmin(CartExportReportMixin, admin.ModelAdmin): 'status_convenio', 'link_sigad', 'data_retorno_assinatura', 'data_termino_vigencia',) list_display_links = ('num_convenio', 'casa_legislativa',) - list_filter = (('casa_legislativa__gerentes_interlegis', - GerentesInterlegisFilter), 'projeto', - 'casa_legislativa__tipo', 'conveniada','equipada', - 'casa_legislativa__municipio__uf',) + list_filter = ( + ('data_retorno_assinatura', DateRangeFilter), + ('data_sigi', DateRangeFilter), ('data_solicitacao', DateRangeFilter), + ('data_sigad', DateRangeFilter), + ('casa_legislativa__gerentes_interlegis', GerentesInterlegisFilter), + 'projeto', 'casa_legislativa__tipo', 'conveniada','equipada', + 'casa_legislativa__municipio__uf', + ) ordering = ('casa_legislativa', '-data_retorno_assinatura') raw_id_fields = ('casa_legislativa',) get_queryset = queryset_ascii From 69b2c6fa3072ac9def46da60ee518fefe04be5fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Sun, 13 Feb 2022 10:17:10 -0300 Subject: [PATCH 8/9] Limpeza da app Casas --- sigi/apps/casas/admin.py | 135 +++++----------------------- sigi/apps/casas/filters.py | 90 ++++++++----------- sigi/apps/casas/reports.py | 179 ------------------------------------- 3 files changed, 59 insertions(+), 345 deletions(-) delete mode 100644 sigi/apps/casas/reports.py diff --git a/sigi/apps/casas/admin.py b/sigi/apps/casas/admin.py index 0de2cd7..96b6933 100644 --- a/sigi/apps/casas/admin.py +++ b/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.admin.options import ModelAdmin from django.contrib.contenttypes.admin import GenericTabularInline -from django.http import HttpResponseRedirect from django.urls import reverse from django.utils.safestring import mark_safe from django.utils.translation import gettext as _ @@ -11,17 +7,14 @@ from django_weasyprint.views import WeasyTemplateResponse from import_export.fields import Field from sigi.apps.casas.forms import OrgaoForm 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, - ExcluirConvenioFilter) + ExcluirConvenioFilter, ServicoFilter) 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.servicos.models import Servico, TipoServico +from sigi.apps.servicos.models import Servico 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 @@ -228,9 +221,9 @@ class ServicoInline(admin.TabularInline): class OcorrenciaInline(admin.TabularInline): model = Ocorrencia fields = ('data_criacao', 'assunto', 'prioridade', 'status', - 'data_modificacao', 'setor_responsavel', 'link_editar',) + 'data_modificacao', 'link_editar',) readonly_fields = ('data_criacao', 'assunto', 'prioridade', 'status', - 'data_modificacao', 'setor_responsavel', 'link_editar',) + 'data_modificacao', 'link_editar',) extra = 0 max_num = 0 can_delete = False @@ -260,12 +253,10 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): list_display = ('id', 'sigla', 'nome', 'get_uf', 'get_gerentes', 'get_convenios', 'get_servicos') 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), - 'municipio__uf__nome', ConvenioFilter, ExcluirConvenioFilter, + 'municipio__uf__nome', ConvenioFilter, ('servico__data_desativacao', ServicoAtivoFilter), + ExcluirConvenioFilter, ServicoFilter, 'inclusao_digital',) ordering = ('municipio__uf__nome', 'nome') queryset = queryset_ascii @@ -318,25 +309,17 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): get_convenios.short_description = _('Convênios') def get_servicos(self, obj): - #TODO: Descomentar após migrar a app Servicos - # return mark_safe( - # '
      ' + - # ''.join( - # [f'
    • {s}
    • ' - # for s in obj.servico_set.filter( - # data_desativacao__isnull=True) - # ] - # ) + - # '
    ' - # ) - 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']} + return mark_safe( + '
      ' + + ''.join( + [f'
    • {s}
    • ' + for s in obj.servico_set.filter( + data_desativacao__isnull=True) + ] + ) + + '
    ' ) + get_servicos.short_description = _('Serviços') def lookup_allowed(self, lookup, value): 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'), 'title': _('Relatório completo') } - print (context) return WeasyTemplateResponse( filename='relatorio_completo.pdf', request=request, @@ -390,85 +372,10 @@ class OrgaoAdmin(CartExportReportMixin, admin.ModelAdmin): ) 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): actions = super(OrgaoAdmin, self).get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] - return actions \ No newline at end of file + return actions + +admin.site.register(TipoOrgao) \ No newline at end of file diff --git a/sigi/apps/casas/filters.py b/sigi/apps/casas/filters.py index 2905b7e..f9aacb4 100644 --- a/sigi/apps/casas/filters.py +++ b/sigi/apps/casas/filters.py @@ -1,14 +1,16 @@ from django.contrib import admin from django.utils.translation import gettext as _ 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): - def __init__(self, *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] class ConvenioFilter(admin.SimpleListFilter): @@ -43,57 +45,41 @@ class ExcluirConvenioFilter(admin.SimpleListFilter): if (self.value() is None): return queryset 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 -# class ServicoFilter(admin.SimpleListFilter): -# title = _("Serviço") -# 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() -# ) +class ServicoFilter(admin.SimpleListFilter): + title = _("Serviço") + parameter_name = 'servico' -# return queryset.distinct('municipio__uf__nome', 'nome') - -# class ServicoAtivoFilter(admin.SimpleListFilter): -# title = _("Serviço ativo") -# parameter_name = 'ativo' + 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 lookups(self, request, model_admin): -# return ( -# ('ativo', _("Ativo")), -# ('desativado', _("Desativado")), -# ) + 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() + ) -# def queryset(self, request, queryset): -# 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 + return queryset.distinct('municipio__uf__nome', 'nome') diff --git a/sigi/apps/casas/reports.py b/sigi/apps/casas/reports.py deleted file mode 100644 index b718055..0000000 --- a/sigi/apps/casas/reports.py +++ /dev/null @@ -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}) - From 96ea3b8f2dd4c7380c7e59f4a0546e6c27b09ffe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ses=C3=B3stris=20Vieira?= Date: Sun, 13 Feb 2022 10:51:26 -0300 Subject: [PATCH 9/9] Melhorar performance filtro por gerentes --- sigi/apps/casas/filters.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sigi/apps/casas/filters.py b/sigi/apps/casas/filters.py index f9aacb4..89f5264 100644 --- a/sigi/apps/casas/filters.py +++ b/sigi/apps/casas/filters.py @@ -7,10 +7,10 @@ from sigi.apps.servicos.models import TipoServico class GerentesInterlegisFilter(admin.filters.RelatedFieldListFilter): def __init__(self, *args, **kwargs): - super(GerentesInterlegisFilter, self).__init__(*args, **kwargs) - gerentes = Servidor.objects.filter( - casas_que_gerencia__isnull=False).order_by( - 'nome_completo').distinct() + super().__init__(*args, **kwargs) + gerentes = Servidor.objects.exclude( + casas_que_gerencia=None).order_by( + 'nome_completo') self.lookup_choices = [(x.id, x) for x in gerentes] class ConvenioFilter(admin.SimpleListFilter):