Browse Source

Prepara app Serviços para migração

revisaoSidenav
Sesostris Vieira 3 years ago
parent
commit
9aa7893387
  1. 170
      sigi/apps/servicos/admin.py
  2. 6
      sigi/apps/servicos/apps.py
  3. 16
      sigi/apps/servicos/migrations/0001_initial.py
  4. 4
      sigi/apps/servicos/migrations/0005_auto_20210406_1945.py
  5. 58
      sigi/apps/servicos/migrations/0009_alter_casamanifesta_email_alter_casamanifesta_id_and_more.py
  6. 30
      sigi/apps/servicos/models.py
  7. 3
      sigi/apps/servicos/tests.py
  8. 1
      sigi/settings/base.py

170
sigi/apps/servicos/admin.py

@ -1,18 +1,16 @@
# -*- coding: utf-8 -*-
from datetime import date, timedelta from datetime import date, timedelta
from django.contrib import admin from django.contrib import admin
from django.core.urlresolvers import reverse 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.forms.models import ModelForm
from django.http import Http404, HttpResponseRedirect from django.http import Http404, HttpResponseRedirect
from django.utils.encoding import force_unicode
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
from sigi.apps.casas.admin import FuncionariosInline, GerentesInterlegisFilter from sigi.apps.casas.admin import FuncionariosInline, GerentesInterlegisFilter
from sigi.apps.casas.models import Orgao from sigi.apps.casas.models import Orgao
from sigi.apps.servicos.models import (Servico, LogServico, CasaAtendida, from sigi.apps.servicos.models import (Servico, LogServico, CasaAtendida,
TipoServico) TipoServico)
from sigi.apps.servicos.views import adicionar_servicos_carrinho
from sigi.apps.utils.base_admin import BaseModelAdmin
class LogServicoInline(admin.StackedInline): class LogServicoInline(admin.StackedInline):
@ -20,9 +18,7 @@ class LogServicoInline(admin.StackedInline):
Fieldset = ((None, {'fields': (('data', 'descricao'), 'log')})) Fieldset = ((None, {'fields': (('data', 'descricao'), 'log')}))
extra = 1 extra = 1
class ServicoFormAdmin(ModelForm): class ServicoFormAdmin(ModelForm):
class Meta: class Meta:
model = Servico model = Servico
fields = '__all__' fields = '__all__'
@ -43,12 +39,14 @@ class ServicoFormAdmin(ModelForm):
if id_casa: if id_casa:
casa = CasaAtendida.objects.get(pk=id_casa) casa = CasaAtendida.objects.get(pk=id_casa)
contatos = [(f.id, unicode(f)) for f in casa.funcionario_set.all()] contatos = [
(f.id, force_str(f)) for f in casa.funcionario_set.all()
]
self.fields['contato_tecnico'].choices = contatos self.fields['contato_tecnico'].choices = contatos
self.fields['contato_administrativo'].choices = contatos self.fields['contato_administrativo'].choices = contatos
@admin.register(TipoServico)
class TipoServicoAdmin(BaseModelAdmin): class TipoServicoAdmin(admin.ModelAdmin):
list_display = ('id', 'sigla', 'nome', 'qtde_casas_atendidas', ) list_display = ('id', 'sigla', 'nome', 'qtde_casas_atendidas', )
ordering = ['id'] ordering = ['id']
@ -111,23 +109,28 @@ class ServicoAtivoFilter(admin.SimpleListFilter):
queryset = queryset.filter(data_desativacao__isnull=False) queryset = queryset.filter(data_desativacao__isnull=False)
return queryset return queryset
class ServicoAdmin(BaseModelAdmin): @admin.register(Servico)
class ServicoAdmin(admin.ModelAdmin):
change_list_template = "servico/change_list.html" change_list_template = "servico/change_list.html"
form = ServicoFormAdmin form = ServicoFormAdmin
actions = ['calcular_data_uso', ] actions = ['calcular_data_uso', ]
list_display = ('casa_legislativa', 'get_codigo_interlegis', 'get_uf', 'tipo_servico', 'hospedagem_interlegis', list_display = ('casa_legislativa', 'get_codigo_interlegis', 'get_uf',
'data_ativacao', 'data_desativacao', 'getUrl', 'data_ultimo_uso', 'get_link_erro') 'tipo_servico', 'hospedagem_interlegis', 'data_ativacao',
'data_desativacao', 'getUrl', 'data_ultimo_uso',
'get_link_erro')
fieldsets = ((None, { fieldsets = ((None, {
'fields': ('casa_legislativa', 'data_ativacao',) 'fields': ('casa_legislativa', 'data_ativacao',)
}), }),
(_('Serviço'), { (_('Serviço'), {
'fields': ('tipo_servico', ('url', 'hospedagem_interlegis'), ('nome_servidor', 'porta_servico', 'senha_inicial'),) 'fields': ('tipo_servico', ('url', 'hospedagem_interlegis'),
('nome_servidor', 'porta_servico', 'senha_inicial'),)
}), }),
(_('Contatos'), { (_('Contatos'), {
'fields': ('contato_tecnico', 'contato_administrativo',) 'fields': ('contato_tecnico', 'contato_administrativo',)
}), }),
(_('Alterações'), { (_('Alterações'), {
'fields': ('data_alteracao', 'data_desativacao', 'motivo_desativacao',) 'fields': ('data_alteracao', 'data_desativacao',
'motivo_desativacao',)
})) }))
readonly_fields = ('casa_legislativa', 'data_ativacao', 'data_alteracao') readonly_fields = ('casa_legislativa', 'data_ativacao', 'data_alteracao')
list_filter = ( list_filter = (
@ -140,14 +143,17 @@ class ServicoAdmin(BaseModelAdmin):
) )
list_display_links = [] list_display_links = []
actions = ['adicionar_servicos'] actions = ['adicionar_servicos']
ordering = ('casa_legislativa__municipio__uf', 'casa_legislativa', 'tipo_servico',) ordering = ('casa_legislativa__municipio__uf', 'casa_legislativa',
'tipo_servico',)
inlines = (LogServicoInline,) inlines = (LogServicoInline,)
search_fields = ('casa_legislativa__search_text',) search_fields = ('casa_legislativa__search_text',)
def get_codigo_interlegis(self, obj): def get_codigo_interlegis(self, obj):
return obj.casa_legislativa.codigo_interlegis return obj.casa_legislativa.codigo_interlegis
get_codigo_interlegis.short_description = _('Código Interlegis') get_codigo_interlegis.short_description = _('Código Interlegis')
get_codigo_interlegis.admin_order_field = 'casa_legislativa__codigo_interlegis' get_codigo_interlegis.admin_order_field = (
'casa_legislativa__codigo_interlegis'
)
def get_uf(self, obj): def get_uf(self, obj):
return '%s' % (obj.casa_legislativa.municipio.uf) return '%s' % (obj.casa_legislativa.municipio.uf)
@ -155,9 +161,8 @@ class ServicoAdmin(BaseModelAdmin):
get_uf.admin_order_field = 'casa_legislativa__municipio__uf' get_uf.admin_order_field = 'casa_legislativa__municipio__uf'
def getUrl(self, obj): def getUrl(self, obj):
return '<a href="%s" target="_blank">%s</a>' % (obj.url, obj.url) return mark_safe(f'<a href="{obj.url}" target="_blank">{obj.url}</a>')
getUrl.short_description = _('Url') getUrl.short_description = _('Url')
getUrl.allow_tags = True
def get_link_erro(self, obj): def get_link_erro(self, obj):
if not obj.erro_atualizacao: if not obj.erro_atualizacao:
@ -167,41 +172,37 @@ class ServicoAdmin(BaseModelAdmin):
url += '/' url += '/'
if obj.tipo_servico.string_pesquisa: if obj.tipo_servico.string_pesquisa:
url += obj.tipo_servico.string_pesquisa.splitlines()[0].split(" ")[0] url += obj.tipo_servico.string_pesquisa.splitlines()[0].split(" ")[0]
return '<a href="%s" target="_blank">%s</a>' % (url, obj.erro_atualizacao) return mark_safe(
get_link_erro.allow_tags = True f'<a href="{url}" target="_blank">{obj.erro_atualizacao}</a>'
)
get_link_erro.short_description = _("Erro na atualização") get_link_erro.short_description = _("Erro na atualização")
get_link_erro.admin_order_field = 'erro_atualizacao' get_link_erro.admin_order_field = 'erro_atualizacao'
def adicionar_servicos(self, request, queryset): # def adicionar_servicos(self, request, queryset):
if 'carrinho_servicos' in request.session: # if 'carrinho_servicos' in request.session:
q1 = len(request.session['carrinho_servicos']) # q1 = len(request.session['carrinho_servicos'])
else: # else:
q1 = 0 # q1 = 0
adicionar_servicos_carrinho(request, queryset=queryset) # adicionar_servicos_carrinho(request, queryset=queryset)
q2 = len(request.session['carrinho_servicos']) # q2 = len(request.session['carrinho_servicos'])
quant = q2 - q1 # quant = q2 - q1
if quant: # if quant:
self.message_user(request, str(q2 - q1) + _(" Serviços adicionados no carrinho")) # self.message_user(request, str(q2 - q1) + _(" Serviços adicionados no carrinho"))
else: # else:
self.message_user(request, _("Os Serviços selecionados já foram adicionadas anteriormente")) # self.message_user(request, _("Os Serviços selecionados já foram adicionadas anteriormente"))
return HttpResponseRedirect('.') # return HttpResponseRedirect('.')
adicionar_servicos.short_description = _("Armazenar serviços no carrinho para exportar") # adicionar_servicos.short_description = _("Armazenar serviços no carrinho para exportar")
def calcular_data_uso(self, request, queryset): def calcular_data_uso(self, request, queryset):
for servico in queryset: for servico in queryset:
servico.atualiza_data_uso() servico.atualiza_data_uso()
self.message_user(request, _("Atualização concluída. Os sites que não responderam foram deixados com a data em branco")) self.message_user(request, _("Atualização concluída. Os sites que não "
"responderam foram deixados com a data "
"em branco"))
return HttpResponseRedirect('.') return HttpResponseRedirect('.')
calcular_data_uso.short_description = _("Atualizar a data do último uso do(s) serviço(s)") calcular_data_uso.short_description = _(
"Atualizar a data do último uso do(s) serviço(s)"
def get_actions(self, request): )
from django.utils.datastructures import SortedDict
actions = [self.get_action(action) for action in self.actions]
actions = filter(None, actions)
actions.sort(lambda a, b: cmp(a[2].lower(), b[2].lower()))
actions = SortedDict([(name, (func, name, desc)) for func, name, desc in actions])
return actions
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
return super(ServicoAdmin, self).lookup_allowed(lookup, value) or \ return super(ServicoAdmin, self).lookup_allowed(lookup, value) or \
@ -213,14 +214,18 @@ class ServicoAdmin(BaseModelAdmin):
if not id_casa: if not id_casa:
raise Http404 raise Http404
return super(ServicoAdmin, self).add_view(request, form_url, extra_context=extra_context) return super(ServicoAdmin, self).add_view(request, form_url,
extra_context=extra_context)
def response_add(self, request, obj): def response_add(self, request, obj):
opts = obj._meta opts = obj._meta
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} msg = (_('The %(name)s "%(obj)s" was added successfully.') %
{'name': force_str(opts.verbose_name),
'obj': force_str(obj)}
)
if "_addanother" in request.POST: if "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_str(opts.verbose_name)))
return HttpResponseRedirect(request.path + '?id_casa=%s' % (obj.casa_legislativa.id,)) return HttpResponseRedirect(request.path + '?id_casa=%s' % (obj.casa_legislativa.id,))
elif "_save" in request.POST: elif "_save" in request.POST:
self.message_user(request, msg) self.message_user(request, msg)
@ -230,10 +235,10 @@ class ServicoAdmin(BaseModelAdmin):
def response_change(self, request, obj): def response_change(self, request, obj):
opts = obj._meta opts = obj._meta
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_str(opts.verbose_name), 'obj': force_str(obj)}
if "_addanother" in request.POST: if "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_str(opts.verbose_name)))
return HttpResponseRedirect("../add/?id_casa=%s" % (obj.casa_legislativa.id,)) return HttpResponseRedirect("../add/?id_casa=%s" % (obj.casa_legislativa.id,))
elif "_save" in request.POST: elif "_save" in request.POST:
self.message_user(request, msg) self.message_user(request, msg)
@ -243,15 +248,11 @@ class ServicoAdmin(BaseModelAdmin):
def save_form(self, request, form, change): def save_form(self, request, form, change):
obj = super(ServicoAdmin, self).save_form(request, form, change) obj = super(ServicoAdmin, self).save_form(request, form, change)
if not change: if not change:
id_casa = request.GET.get('id_casa', None) id_casa = request.GET.get('id_casa', None)
if not id_casa: if not id_casa:
raise Http404 raise Http404
obj.casa_legislativa = Orgao.objects.get(pk=id_casa) obj.casa_legislativa = Orgao.objects.get(pk=id_casa)
return obj return obj
def changelist_view(self, request, extra_context=None): def changelist_view(self, request, extra_context=None):
@ -266,22 +267,20 @@ class ServicoAdmin(BaseModelAdmin):
extra_context={'query_str': '?' + request.META['QUERY_STRING']} extra_context={'query_str': '?' + request.META['QUERY_STRING']}
) )
def adicionar_servicos(self, request, queryset): # def adicionar_servicos(self, request, queryset):
if 'carrinho_servicos' in request.session: # if 'carrinho_servicos' in request.session:
q1 = len(request.session['carrinho_servicos']) # q1 = len(request.session['carrinho_servicos'])
else: # else:
q1 = 0 # q1 = 0
adicionar_servicos_carrinho(request, queryset=queryset) # adicionar_servicos_carrinho(request, queryset=queryset)
q2 = len(request.session['carrinho_servicos']) # q2 = len(request.session['carrinho_servicos'])
quant = q2 - q1 # quant = q2 - q1
if quant: # if quant:
self.message_user(request, str(q2 - q1) + _(" Convênios adicionados no carrinho")) # self.message_user(request, str(q2 - q1) + _(" Convênios adicionados no carrinho"))
else: # else:
self.message_user(request, _("Os Convênios selecionados já foram adicionadas anteriormente")) # self.message_user(request, _("Os Convênios selecionados já foram adicionadas anteriormente"))
return HttpResponseRedirect('.') # return HttpResponseRedirect('.')
adicionar_servicos.short_description = _("Armazenar Serviços no carrinho para exportar") # adicionar_servicos.short_description = _("Armazenar Serviços no carrinho para exportar")
class ContatosInline(FuncionariosInline): class ContatosInline(FuncionariosInline):
can_delete = False # Equipe do SEIT não pode excluir pessoas de contato can_delete = False # Equipe do SEIT não pode excluir pessoas de contato
@ -296,14 +295,16 @@ class ContatosInline(FuncionariosInline):
# 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 # 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(BaseModelAdmin): class CasaAtendidaAdmin(admin.ModelAdmin):
actions = None actions = None
list_display = ('codigo_interlegis', 'nome', 'get_servicos',) list_display = ('codigo_interlegis', 'nome', 'get_servicos',)
ordering = ['nome'] ordering = ['nome']
fieldsets = ( fieldsets = (
('Casa Legislativa', { ('Casa Legislativa', {
'fields': (('codigo_interlegis', 'nome'), ('logradouro', 'bairro', 'municipio', 'cep'), ('email', 'pagina_web')) 'fields': (('codigo_interlegis', 'nome'), ('logradouro', 'bairro',
'municipio', 'cep'),
('email', 'pagina_web'))
}),) }),)
readonly_fields = ('nome', 'logradouro', 'bairro', 'municipio', 'cep') readonly_fields = ('nome', 'logradouro', 'bairro', 'municipio', 'cep')
inlines = (ContatosInline,) inlines = (ContatosInline,)
@ -314,16 +315,13 @@ class CasaAtendidaAdmin(BaseModelAdmin):
'municipio__codigo_ibge', 'pagina_web', 'observacoes') 'municipio__codigo_ibge', 'pagina_web', 'observacoes')
def get_servicos(self, obj): def get_servicos(self, obj):
result = [] result = [
for servico in obj.servico_set.all(): f"{servico.tipo_servico.nome} ({servico.status_servico}). "
result.append("%s (%s). %s: %s" % ( f"Contato: {servico.contato_administrativo.nome}"
servico.tipo_servico.nome, for servico in obj.servico_set.all()
_('ativo') if servico.data_desativacao is None else _('desativado'), ]
_('Contato'),
servico.contato_administrativo.nome)) return mark_safe("<ul><li>" + "</li><li>".join(result) + "</li></ul>")
return "<ul><li>" + "</li><li>".join(result) + "</li></ul>"
get_servicos.allow_tags = True
get_servicos.short_description = _("Serviços") get_servicos.short_description = _("Serviços")
def lookup_allowed(self, lookup, value): def lookup_allowed(self, lookup, value):
@ -345,7 +343,3 @@ class CasaAtendidaAdmin(BaseModelAdmin):
def has_delete_permission(self, request, obj=None): def has_delete_permission(self, request, obj=None):
return False # Nunca deletar casas por aqui return False # Nunca deletar casas por aqui
admin.site.register(Servico, ServicoAdmin)
admin.site.register(TipoServico, TipoServicoAdmin)
admin.site.register(CasaAtendida, CasaAtendidaAdmin)

6
sigi/apps/servicos/apps.py

@ -0,0 +1,6 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ServicosConfig(AppConfig):
name = 'sigi.apps.servicos'
verbose_name = _('serviços SEIT')

16
sigi/apps/servicos/migrations/0001_initial.py

@ -21,7 +21,7 @@ class Migration(migrations.Migration):
('informante', models.CharField(max_length=100, verbose_name='Nome do informante', blank=True)), ('informante', models.CharField(max_length=100, verbose_name='Nome do informante', blank=True)),
('cargo', models.CharField(max_length=100, verbose_name='Cargo do informante', blank=True)), ('cargo', models.CharField(max_length=100, verbose_name='Cargo do informante', blank=True)),
('email', models.EmailField(max_length=75, verbose_name='E-mail de contato', blank=True)), ('email', models.EmailField(max_length=75, verbose_name='E-mail de contato', blank=True)),
('casa_legislativa', models.OneToOneField(to='casas.CasaLegislativa')), ('casa_legislativa', models.OneToOneField(to='casas.CasaLegislativa', on_delete=models.CASCADE)),
], ],
options={ options={
}, },
@ -70,9 +70,9 @@ class Migration(migrations.Migration):
('motivo_desativacao', models.TextField(verbose_name='Motivo da desativa\xe7\xe3o', blank=True)), ('motivo_desativacao', models.TextField(verbose_name='Motivo da desativa\xe7\xe3o', blank=True)),
('data_ultimo_uso', models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez<br/><strong>N\xc3O \xc9 ATUALIZADO AUTOMATICAMENTE!</strong>', null=True, verbose_name='Data da \xfaltima utiliza\xe7\xe3o', blank=True)), ('data_ultimo_uso', models.DateField(help_text='Data em que o servi\xe7o foi utilizado pela Casa Legislativa pela \xfaltima vez<br/><strong>N\xc3O \xc9 ATUALIZADO AUTOMATICAMENTE!</strong>', null=True, verbose_name='Data da \xfaltima utiliza\xe7\xe3o', blank=True)),
('erro_atualizacao', models.CharField(help_text='Erro ocorrido na \xfaltima tentativa de atualizar a data de \xfaltimo acesso', max_length=200, verbose_name='Erro na atualiza\xe7\xe3o', blank=True)), ('erro_atualizacao', models.CharField(help_text='Erro ocorrido na \xfaltima tentativa de atualizar a data de \xfaltimo acesso', max_length=200, verbose_name='Erro na atualiza\xe7\xe3o', blank=True)),
('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa')), ('casa_legislativa', models.ForeignKey(verbose_name='Casa Legislativa', to='casas.CasaLegislativa', on_delete=models.CASCADE)),
('contato_administrativo', models.ForeignKey(related_name=b'contato_administrativo', verbose_name='Contato administrativo', to='casas.Funcionario')), ('contato_administrativo', models.ForeignKey(related_name=b'contato_administrativo', verbose_name='Contato administrativo', to='casas.Funcionario', on_delete=models.CASCADE)),
('contato_tecnico', models.ForeignKey(related_name=b'contato_tecnico', verbose_name='Contato t\xe9cnico', to='casas.Funcionario')), ('contato_tecnico', models.ForeignKey(related_name=b'contato_tecnico', verbose_name='Contato t\xe9cnico', to='casas.Funcionario', on_delete=models.CASCADE)),
], ],
options={ options={
}, },
@ -84,7 +84,7 @@ class Migration(migrations.Migration):
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('url', models.URLField(blank=True)), ('url', models.URLField(blank=True)),
('hospedagem_interlegis', models.BooleanField(default=False, verbose_name='Hospedagem no Interlegis?')), ('hospedagem_interlegis', models.BooleanField(default=False, verbose_name='Hospedagem no Interlegis?')),
('casa_manifesta', models.ForeignKey(to='servicos.CasaManifesta')), ('casa_manifesta', models.ForeignKey(to='servicos.CasaManifesta', on_delete=models.CASCADE)),
], ],
options={ options={
}, },
@ -110,7 +110,7 @@ class Migration(migrations.Migration):
migrations.AddField( migrations.AddField(
model_name='servicomanifesto', model_name='servicomanifesto',
name='servico', name='servico',
field=models.ForeignKey(to='servicos.TipoServico'), field=models.ForeignKey(to='servicos.TipoServico', on_delete=models.CASCADE),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterUniqueTogether( migrations.AlterUniqueTogether(
@ -120,13 +120,13 @@ class Migration(migrations.Migration):
migrations.AddField( migrations.AddField(
model_name='servico', model_name='servico',
name='tipo_servico', name='tipo_servico',
field=models.ForeignKey(verbose_name='Tipo de servi\xe7o', to='servicos.TipoServico'), field=models.ForeignKey(verbose_name='Tipo de servi\xe7o', to='servicos.TipoServico', on_delete=models.CASCADE),
preserve_default=True, preserve_default=True,
), ),
migrations.AddField( migrations.AddField(
model_name='logservico', model_name='logservico',
name='servico', name='servico',
field=models.ForeignKey(verbose_name='Servi\xe7o', to='servicos.Servico'), field=models.ForeignKey(verbose_name='Servi\xe7o', to='servicos.Servico', on_delete=models.CASCADE),
preserve_default=True, preserve_default=True,
), ),
migrations.CreateModel( migrations.CreateModel(

4
sigi/apps/servicos/migrations/0005_auto_20210406_1945.py

@ -15,13 +15,13 @@ class Migration(migrations.Migration):
migrations.AlterField( migrations.AlterField(
model_name='casamanifesta', model_name='casamanifesta',
name='casa_legislativa', name='casa_legislativa',
field=models.OneToOneField(to='casas.Orgao'), field=models.OneToOneField(to='casas.Orgao', on_delete=models.CASCADE),
preserve_default=True, preserve_default=True,
), ),
migrations.AlterField( migrations.AlterField(
model_name='servico', model_name='servico',
name='casa_legislativa', name='casa_legislativa',
field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao'), field=models.ForeignKey(verbose_name='Casa Legislativa', to='casas.Orgao', on_delete=models.CASCADE),
preserve_default=True, preserve_default=True,
), ),
] ]

58
sigi/apps/servicos/migrations/0009_alter_casamanifesta_email_alter_casamanifesta_id_and_more.py

@ -0,0 +1,58 @@
# Generated by Django 4.0.1 on 2022-01-17 23:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('servicos', '0008_auto_20210519_1117'),
]
operations = [
migrations.AlterField(
model_name='casamanifesta',
name='email',
field=models.EmailField(blank=True, max_length=254, verbose_name='E-mail de contato'),
),
migrations.AlterField(
model_name='casamanifesta',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='logservico',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='registroservico',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='servico',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='servicomanifesto',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='tiposervico',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='tiposervico',
name='modo',
field=models.CharField(choices=[('H', 'Hospedagem'), ('R', 'Registro')], max_length=1, verbose_name='modo de prestação do serviço'),
),
migrations.AlterField(
model_name='tiposervico',
name='sigla',
field=models.CharField(max_length=12, verbose_name='sigla'),
),
]

30
sigi/apps/servicos/models.py

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from datetime import date from datetime import date
from django.db import models from django.db import models
from sigi.apps.casas.models import Orgao, Funcionario from sigi.apps.casas.models import Orgao, Funcionario
@ -19,7 +17,7 @@ class TipoServico(models.Model):
"<ul><li>/caminho/da/pesquisa/?parametros " "<ul><li>/caminho/da/pesquisa/?parametros "
"[xml|json] campo.de.data</li>") "[xml|json] campo.de.data</li>")
nome = models.CharField(_('nome'), max_length=60) nome = models.CharField(_('nome'), max_length=60)
sigla = models.CharField(_('sigla'), max_length='12') sigla = models.CharField(_('sigla'), max_length=12)
modo = models.CharField( modo = models.CharField(
_('modo de prestação do serviço'), _('modo de prestação do serviço'),
max_length=1, max_length=1,
@ -43,10 +41,9 @@ class TipoServico(models.Model):
verbose_name = _('Tipo de serviço') verbose_name = _('Tipo de serviço')
verbose_name_plural = _('Tipos de serviço') verbose_name_plural = _('Tipos de serviço')
def __unicode__(self): def __str__(self):
return self.nome return self.nome
class Servico(models.Model): class Servico(models.Model):
casa_legislativa = models.ForeignKey( casa_legislativa = models.ForeignKey(
Orgao, Orgao,
@ -122,7 +119,12 @@ class Servico(models.Model):
"de última atualização do serviço") "de última atualização do serviço")
) )
# casa_legislativa.casa_uf_filter = True @property
def status_servico(self):
if self.data_desativacao is None:
return _("Ativo")
else:
return _("Inativo")
def atualiza_data_uso(self): def atualiza_data_uso(self):
import requests import requests
@ -247,8 +249,8 @@ class Servico(models.Model):
return return
def __unicode__(self): def __str__(self):
return "%s (%s)" % (self.tipo_servico.nome, _('ativo') if self.data_desativacao is None else _('Desativado')) return f"{self.tipo_servico.nome} ({self.status_servico})"
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
# Reter o objeto original para verificar mudanças # Reter o objeto original para verificar mudanças
@ -290,7 +292,6 @@ class Servico(models.Model):
return return
class LogServico(models.Model): class LogServico(models.Model):
servico = models.ForeignKey( servico = models.ForeignKey(
Servico, Servico,
@ -301,31 +302,26 @@ class LogServico(models.Model):
data = models.DateField(_('Data da ação'), default=date.today) data = models.DateField(_('Data da ação'), default=date.today)
log = models.TextField(_('Log da ação')) log = models.TextField(_('Log da ação'))
def __unicode__(self): def __str__(self):
return "%s (%s)" % (self.descricao, self.data) return f"{self.descricao} ({self.data})"
class Meta: class Meta:
verbose_name = _('Log do serviço') verbose_name = _('Log do serviço')
verbose_name_plural = _('Logs do serviço') verbose_name_plural = _('Logs do serviço')
class CasaAtendidaManager(models.Manager): class CasaAtendidaManager(models.Manager):
def get_queryset(self): def get_queryset(self):
qs = super(CasaAtendidaManager, self).get_queryset() qs = super(CasaAtendidaManager, self).get_queryset()
qs = qs.exclude(codigo_interlegis='') qs = qs.exclude(codigo_interlegis='')
return qs return qs
class CasaAtendida(Orgao): class CasaAtendida(Orgao):
class Meta: class Meta:
proxy = True proxy = True
verbose_name_plural = _('Casas atendidas') verbose_name_plural = _('Casas atendidas')
objects = CasaAtendidaManager() objects = CasaAtendidaManager()
class CasaManifesta(models.Model): class CasaManifesta(models.Model):
casa_legislativa = models.OneToOneField(Orgao, on_delete=models.CASCADE) casa_legislativa = models.OneToOneField(Orgao, on_delete=models.CASCADE)
data_manifestacao = models.DateTimeField(auto_now_add=True) data_manifestacao = models.DateTimeField(auto_now_add=True)
@ -334,7 +330,6 @@ class CasaManifesta(models.Model):
cargo = models.CharField(_('Cargo do informante'), max_length=100, blank=True) cargo = models.CharField(_('Cargo do informante'), max_length=100, blank=True)
email = models.EmailField(_('E-mail de contato'), blank=True) email = models.EmailField(_('E-mail de contato'), blank=True)
class ServicoManifesto(models.Model): class ServicoManifesto(models.Model):
casa_manifesta = models.ForeignKey(CasaManifesta, on_delete=models.CASCADE) casa_manifesta = models.ForeignKey(CasaManifesta, on_delete=models.CASCADE)
servico = models.ForeignKey(TipoServico, on_delete=models.CASCADE) servico = models.ForeignKey(TipoServico, on_delete=models.CASCADE)
@ -344,7 +339,6 @@ class ServicoManifesto(models.Model):
class Meta: class Meta:
unique_together = ('casa_manifesta', 'servico') unique_together = ('casa_manifesta', 'servico')
class RegistroServico(models.Model): class RegistroServico(models.Model):
produto = models.CharField(max_length=50) produto = models.CharField(max_length=50)
versao = models.CharField(max_length=30) versao = models.CharField(max_length=30)

3
sigi/apps/servicos/tests.py

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

1
sigi/settings/base.py

@ -25,6 +25,7 @@ INSTALLED_APPS = [
'sigi.apps.casas', 'sigi.apps.casas',
'sigi.apps.convenios', 'sigi.apps.convenios',
'sigi.apps.inventario', 'sigi.apps.inventario',
'sigi.apps.servicos',
'localflavor', 'localflavor',
'import_export', 'import_export',
'django_bootstrap5', 'django_bootstrap5',

Loading…
Cancel
Save