Skip to content

Commit

Permalink
func: get do historico de alertas com filtragem por estação e por tim…
Browse files Browse the repository at this point in the history
…estamp
  • Loading branch information
ryandaraujo authored and iagocpv committed Nov 8, 2024
1 parent 9501e3d commit 405b9a2
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 49 deletions.
15 changes: 12 additions & 3 deletions src/tupan/alertas/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,20 @@ class AlertaAdmin(admin.ModelAdmin):
class HistoricoAlertaAdmin(admin.ModelAdmin):
list_display = [
"alerta",
"medicao",
"timestamp",
"timestamp_convertido",
"criado",
"modificado",
]
list_filter = [
"alerta",
"modificado",
"criado",
]
readonly_fields = [
"criado",
"timestamp_convertido",
"modificado"
]


Expand All @@ -45,12 +49,17 @@ class MedicaoAdmin(admin.ModelAdmin):
list_display = [
"dados",
"timestamp",
"estacao_parametro",
"timestamp_convertido",
"criado",
"modificado",
]
list_filter = [
"modificado",
"dados",
"timestamp_convertido",
"criado",
]
readonly_fields = [
"criado",
"timestamp_convertido",
"modificado"
]
3 changes: 3 additions & 0 deletions src/tupan/alertas/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class Meta:
verbose_name = "Medição"
verbose_name_plural = "Medições"

def __str__(self) -> str:
return f"{self.dados} - {self.estacao_parametro}"

def save(self, *args, **kwargs):
self.timestamp_convertido = datetime.fromtimestamp(self.timestamp)
super(Medicao, self).save(*args, **kwargs)
Expand Down
4 changes: 3 additions & 1 deletion src/tupan/alertas/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from rest_framework import serializers
from .models import Alerta, Medicao, HistoricoAlerta
from estacoes.serializers import EstacaoParametroSerializer
from estacoes.serializers import EstacaoParametroSerializer, EstacaoSerializer

class AlertaSerializer(serializers.ModelSerializer):
class Meta:
Expand All @@ -15,6 +15,8 @@ class Meta:
fields = ('id', 'timestamp', 'timestamp_convertido', 'dados', 'estacao_parametro')

class HistoricoAlertaSerializer(serializers.ModelSerializer):
estacao = EstacaoSerializer(source='alerta.estacao_parametro.estacao', read_only=True)

class Meta:
model = HistoricoAlerta
fields = '__all__'
58 changes: 14 additions & 44 deletions src/tupan/alertas/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ def delete(self, request, id, *args, **kwargs):
class HistoricoAlertaView(APIView):
@extend_schema(
parameters=[
OpenApiParameter("timestamp_inicial", description="Timestamp inicial para filtragem", required=False, type=str),
OpenApiParameter("timestamp_final", description="Timestamp final para filtragem", required=False, type=str),
OpenApiParameter("timestamp", description="Timestamp para filtragem", required=False, type=str),
OpenApiParameter("estacao_id", description="ID da estação para filtragem", required=False, type=int)
],
Expand All @@ -151,64 +153,32 @@ class HistoricoAlertaView(APIView):
)
def get(self, request, *args, **kwargs):
try:
timestamp_inicial = request.query_params.get("timestamp_inicial")
timestamp_final = request.query_params.get("timestamp_final")
timestamp = request.query_params.get("timestamp")
estacao_id = request.query_params.get("estacao_id")

historico = HistoricoAlerta.objects.select_related('alerta__estacao_parametro__estacao').all()

if timestamp_inicial and timestamp_final:
historico = historico.filter(timestamp__range=[timestamp_inicial, timestamp_final])
elif timestamp_inicial:
historico = historico.filter(timestamp__gte=timestamp_inicial)
elif timestamp_final:
historico = historico.filter(timestamp__lte=timestamp_final)

if timestamp:
historico = historico.filter(timestamp=timestamp)

if estacao_id:
historico = historico.filter(alerta__estacao_parametro__estacao__id=estacao_id)

resultado = [
{
"id_historico_alerta": h.id,
"timestamp": h.timestamp,
"estacao": h.alerta.estacao_parametro.estacao
}
for h in historico
]
serializer = HistoricoAlertaSerializer(historico, many=True)

return JsonResponse(resultado, safe=False)
return JsonResponse(data=serializer.data, safe=False)
except Exception as e:
return JsonResponse({'error': f'Erro ao buscar dados: {str(e)}'}, status=500)

@extend_schema(
request=OpenApiRequest(HistoricoAlertaSerializer),
responses={
200: OpenApiResponse(HistoricoAlertaSerializer),
400: OpenApiResponse(description="Campos obrigatórios: timestamp, alerta | Dados inválidos"),
404: OpenApiResponse(description="Alerta não encontrado"),
500: OpenApiResponse(description="Erro ao salvar histórico")
}
)
def post(self, request, *args, **kwargs):
try:
data = json.loads(request.body)
timestamp = data.get('timestamp')
alerta_id = data.get('alerta')

if not timestamp or not alerta_id:
return JsonResponse({'error': 'Campos obrigatórios: timestamp, alerta'}, status=400)

alerta = Alerta.objects.get(pk=alerta_id)
hist = HistoricoAlerta(timestamp=timestamp, alerta=alerta)
hist.save()

return JsonResponse({
'id': hist.pk,
'timestamp': hist.timestamp,
'alerta': hist.alerta.pk,
'timestamp_convertido': hist.timestamp_convertido
}, status=201)
except Alerta.DoesNotExist:
return JsonResponse({'error': 'Alerta não encontrado'}, status=404)
except json.JSONDecodeError:
return JsonResponse({'error': 'Dados inválidos'}, status=400)
except Exception as e:
return JsonResponse({'error': f'Erro ao salvar histórico: {str(e)}'}, status=500)


class MedicaoView(APIView):
@extend_schema(
Expand Down
9 changes: 8 additions & 1 deletion src/tupan/estacoes/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.contrib import admin

from .models import Endereco, Estacao, Parametro, Categoria
from .models import Endereco, Estacao, Parametro, Categoria, EstacaoParametro

@admin.register(Parametro)
class ParametroAdmin(admin.ModelAdmin):
Expand Down Expand Up @@ -57,6 +57,11 @@ class EnderecoAdmin(admin.ModelAdmin):
"modificado"
]


class EstacaoParametroInline(admin.TabularInline):
model = EstacaoParametro
extra = 1

@admin.register(Estacao)
class EstacaoAdmin(admin.ModelAdmin):
list_display = [
Expand All @@ -77,6 +82,8 @@ class EstacaoAdmin(admin.ModelAdmin):
"modificado"
]

inlines = [EstacaoParametroInline]

def getParametros(self, obj):
return ", ".join([parametro.nome for parametro in obj.parametros.all()])

Expand Down
3 changes: 3 additions & 0 deletions src/tupan/estacoes/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,6 @@ class EstacaoParametro(models.Model):
parametro = models.ForeignKey(Parametro, on_delete=models.CASCADE)
class Meta:
db_table = "estacoes_estacao_parametro"

def __str__(self):
return f"{self.estacao.nome} - {self.parametro.nome}"

0 comments on commit 405b9a2

Please sign in to comment.