Skip to content

Commit

Permalink
Merge pull request #17 refa/otimizacao-5
Browse files Browse the repository at this point in the history
Refa/otimizacao 5
  • Loading branch information
ryandaraujo authored Oct 18, 2024
2 parents 321507e + f6c5fe0 commit 23020fa
Show file tree
Hide file tree
Showing 21 changed files with 255 additions and 277 deletions.
28 changes: 23 additions & 5 deletions src/tupan/alertas/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.1.1 on 2024-09-12 01:45
# Generated by Django 5.1.1 on 2024-10-08 09:52

import django.db.models.deletion
from django.db import migrations, models
Expand All @@ -9,6 +9,7 @@ class Migration(migrations.Migration):
initial = True

dependencies = [
('estacoes', '0001_initial'),
]

operations = [
Expand All @@ -18,9 +19,10 @@ class Migration(migrations.Migration):
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('nome', models.CharField(help_text='nome do alerta', max_length=127, unique=True)),
('condicao', models.CharField(help_text='condição para o alerta acontecer', max_length=4)),
('nome', models.CharField(help_text='Nome do alerta', max_length=127, unique=True)),
('condicao', models.CharField(help_text='Condição para o alerta acontecer', max_length=4)),
('ativo', models.BooleanField(default=True)),
('estacao_parametro', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='estacoes.estacaoparametro')),
],
options={
'verbose_name': 'Alerta',
Expand All @@ -33,13 +35,29 @@ class Migration(migrations.Migration):
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('timestamp', models.BigIntegerField()),
('timestamp_convertido', models.DateTimeField(blank=True, null=True)),
('timestamp', models.BigIntegerField(help_text='Data/hora do alerta em timestamp')),
('timestamp_convertido', models.DateTimeField(blank=True, help_text='Data/hora do alerta em datetime', null=True)),
('alerta', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='historico_alertas', to='alertas.alerta')),
],
options={
'verbose_name': 'Histórico de Alerta',
'verbose_name_plural': 'Históricos de Alertas',
},
),
migrations.CreateModel(
name='Medicao',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('timestamp', models.BigIntegerField(help_text='Data/hora da medição em timestamp')),
('timestamp_convertido', models.DateTimeField(blank=True, help_text='Data/hora da medição em datetime', null=True)),
('dados', models.CharField(help_text='Valor dos dados da medição', max_length=63)),
('estacao_parametro', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='estacoes.estacaoparametro')),
],
options={
'verbose_name': 'Medição',
'verbose_name_plural': 'Medições',
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 5.1.1 on 2024-10-09 08:05

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('alertas', '0001_initial'),
('estacoes', '0002_alter_estacaoparametro_table'),
]

operations = [
migrations.AlterField(
model_name='alerta',
name='estacao_parametro',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='estacoes.estacaoparametro'),
),
]
28 changes: 0 additions & 28 deletions src/tupan/alertas/migrations/0002_medicao.py

This file was deleted.

5 changes: 3 additions & 2 deletions src/tupan/alertas/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.db import models
from datetime import datetime
from estacoes.models import EstacaoParametro


class Base(models.Model):
Expand All @@ -14,7 +15,7 @@ class Alerta(Base):
nome = models.CharField(help_text="Nome do alerta", max_length=127, unique=True)
condicao = models.CharField(help_text="Condição para o alerta acontecer", max_length=4)
ativo = models.BooleanField(default=True)
# falta a chave estrangeira da estacao_parametro
estacao_parametro = models.ForeignKey(EstacaoParametro, on_delete=models.CASCADE)

class Meta:
verbose_name = "Alerta"
Expand Down Expand Up @@ -42,7 +43,7 @@ class Medicao(Base):
timestamp = models.BigIntegerField(help_text="Data/hora da medição em timestamp", blank=False)
timestamp_convertido = models.DateTimeField(help_text="Data/hora da medição em datetime", blank=True, null=True)
dados = models.CharField(help_text="Valor dos dados da medição", max_length=63, blank=False, null=False)
# Falta a chave estrangeira estacao_parametro
estacao_parametro = models.ForeignKey(EstacaoParametro, on_delete=models.CASCADE, default=1)

class Meta:
verbose_name = "Medição"
Expand Down
8 changes: 8 additions & 0 deletions src/tupan/alertas/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from rest_framework import serializers
from .models import Alerta

class AlertaSerializer(serializers.ModelSerializer):
class Meta:
model = Alerta
fields = ('id', 'nome', 'condicao', 'estacao_parametro', 'criado', 'modificado', 'ativo')
read_only_fields = ['estacao_parametro']
4 changes: 2 additions & 2 deletions src/tupan/alertas/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from .views import AlertasView, AlertasDetalhesView, HistoricoAlertaView, MedicaoView, MedicaoDetalhesView

urlpatterns = [
path('', AlertasView.as_view(), name='alertas'),
path('<int:id>', AlertasDetalhesView.as_view(), name='alertas-detalhes'),
path('alertas', AlertasView.as_view(), name='alertas'),
path('alertas/<int:id>', AlertasDetalhesView.as_view(), name='alertas-detalhes'),
path('historicos', HistoricoAlertaView.as_view(), name='historico-alertas'),
path('medicoes', MedicaoView.as_view(), name='medicoes'),
path('medicoes/<int:id>', MedicaoDetalhesView.as_view(), name='medicoes-detalhes')
Expand Down
40 changes: 20 additions & 20 deletions src/tupan/alertas/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
import json
from estacoes.models import EstacaoParametro
from .serializers import AlertaSerializer
from .models import Alerta, HistoricoAlerta, Medicao
from django.core.exceptions import ValidationError


class AlertasView(APIView):

def get(self, request, *args, **kwargs):
try:
# Obtém o valor do parâmetro 'ativo' da requisição, se disponível
Expand Down Expand Up @@ -35,25 +40,25 @@ def get(self, request, *args, **kwargs):
'data': f"{e}"
}, status=500)


def post(self, request, *args, **kwargs):
try:
data = json.loads(request.body)
nome = data.get('nome')
condicao = data.get('condicao')
ativo = data.get('ativo')

parametro_estacao = data.get('estacao_parametro')
estacao_parametro = EstacaoParametro.objects.get(estacao = parametro_estacao['estacao'], parametro = parametro_estacao['parametro'])
if not nome or not condicao:
return JsonResponse({'error': 'Campos obrigatórios: nome, condicao'}, status=400)

alerta = Alerta(nome=nome, condicao=condicao)
alerta.save()

return JsonResponse({
'id': alerta.pk,
'nome': alerta.nome,
'condicao': alerta.condicao,
'ativo': alerta.ativo
}, status=201)

alerta = Alerta(nome=nome, condicao=condicao, ativo=ativo, estacao_parametro=estacao_parametro)
serializer = AlertaSerializer(alerta, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except json.JSONDecodeError:
return JsonResponse({'error': 'Dados inválidos'}, status=400)

Expand All @@ -71,18 +76,13 @@ def get(self, request, id, *args, **kwargs):

def put(self, request, id, *args, **kwargs):
try:
data = json.loads(request.body)
alerta = Alerta.objects.filter(id=id, ativo=True).first()
if alerta:
alerta.nome = data.get('nome', alerta.nome)
alerta.condicao = data.get('condicao', alerta.condicao)
alerta.save()
return JsonResponse({
'id': alerta.pk,
'nome': alerta.nome,
'condicao': alerta.condicao,
'ativo': alerta.ativo
}, status=200)
serializer = AlertaSerializer(alerta, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return JsonResponse({'error': 'Alerta não encontrado ou inativo'}, status=404)
except json.JSONDecodeError:
Expand Down
17 changes: 14 additions & 3 deletions src/tupan/estacoes/admin.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
from django.contrib import admin

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

@admin.register(Parametro)
class ParametroAdmin(admin.ModelAdmin):
list_display = [
"nome",
"fator",
"offset",
"unidade",
"nome_json",
"criado",
"modificado",
]
list_filter = [
"modificado",
"nome",
"unidade",
"criado"
]
readonly_fields = [
"criado",
"modificado"
]


@admin.register(Categoria)
class CategoriaAdmin(admin.ModelAdmin):
list_display = [
"unidade",
"nome"
]
list_filter = [
"unidade"
]


@admin.register(Endereco)
class EnderecoAdmin(admin.ModelAdmin):
list_display = [
Expand Down
57 changes: 45 additions & 12 deletions src/tupan/estacoes/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.1.1 on 2024-09-26 22:15
# Generated by Django 5.1.1 on 2024-10-08 09:52

import django.db.models.deletion
from django.db import migrations, models
Expand All @@ -12,12 +12,28 @@ class Migration(migrations.Migration):
]

operations = [
migrations.CreateModel(
name='Categoria',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('ativo', models.BooleanField(default=True)),
('unidade', models.CharField(help_text='Unidade de medida do parâmetro', max_length=30)),
('nome', models.CharField(help_text='Nome da categoria do parâmetro', max_length=127)),
],
options={
'verbose_name': 'Categoria',
'verbose_name_plural': 'Categorias',
},
),
migrations.CreateModel(
name='Endereco',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('ativo', models.BooleanField(default=True)),
('logradouro', models.CharField(max_length=127)),
('bairro', models.CharField(max_length=127)),
('cidade', models.CharField(max_length=127)),
Expand All @@ -33,38 +49,55 @@ class Migration(migrations.Migration):
'verbose_name_plural': 'Endereços',
},
),
migrations.CreateModel(
name='Estacao',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('ativo', models.BooleanField(default=True)),
('nome', models.CharField(max_length=127)),
('topico', models.CharField(help_text='Tópico do broker MQTT', max_length=127)),
('endereco', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='estacoes.endereco')),
],
options={
'verbose_name': 'Estação',
'verbose_name_plural': 'Estações',
},
),
migrations.CreateModel(
name='Parametro',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('ativo', models.BooleanField(default=True)),
('nome', models.CharField(max_length=127)),
('fator', models.DecimalField(decimal_places=4, default=1, help_text='Valor a ser multiplicado', max_digits=10)),
('offset', models.DecimalField(decimal_places=4, default=0, help_text='Valor a ser adicionado', max_digits=10)),
('unidade', models.CharField(max_length=30)),
('nome_json', models.CharField(help_text='Nome do campo no json', max_length=127)),
('descricao', models.TextField(blank=True, help_text='Descrição do que abrange o parâmetro', max_length=255)),
('categoria', models.ForeignKey(default=None, help_text='Tipo do parametro e unidade', on_delete=django.db.models.deletion.CASCADE, to='estacoes.categoria')),
],
options={
'verbose_name': 'Parâmetro',
'verbose_name_plural': 'Parâmetros',
},
),
migrations.CreateModel(
name='Estacao',
name='EstacaoParametro',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('criado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now=True)),
('nome', models.CharField(max_length=127)),
('topico', models.CharField(help_text='Tópico do broker MQTT', max_length=127)),
('ativo', models.BooleanField(default=True)),
('endereco', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='estacoes.endereco')),
('parametros', models.ManyToManyField(blank=True, to='estacoes.parametro')),
('estacao', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='estacoes.estacao')),
('parametro', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='estacoes.parametro')),
],
options={
'verbose_name': 'Estação',
'verbose_name_plural': 'Estações',
'db_table': 'estacoes_estacao_parametros',
},
),
migrations.AddField(
model_name='estacao',
name='parametros',
field=models.ManyToManyField(blank=True, through='estacoes.EstacaoParametro', to='estacoes.parametro'),
),
]
17 changes: 17 additions & 0 deletions src/tupan/estacoes/migrations/0002_alter_estacaoparametro_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 5.1.1 on 2024-10-08 10:12

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('estacoes', '0001_initial'),
]

operations = [
migrations.AlterModelTable(
name='estacaoparametro',
table='estacoes_estacao_parametro',
),
]
Loading

0 comments on commit 23020fa

Please sign in to comment.