Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/115/task/vincular-um-chat-especí…
Browse files Browse the repository at this point in the history
…fico-a-um-item-cadastrado-na-plataforma'
  • Loading branch information
314dro committed Jan 9, 2025
2 parents a5e0c5c + 8b24398 commit f1f5c27
Show file tree
Hide file tree
Showing 24 changed files with 77 additions and 14 deletions.
Binary file removed API/AcheiUnB/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file removed API/AcheiUnB/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file removed API/AcheiUnB/__pycache__/settings.cpython-310.pyc
Binary file not shown.
Binary file removed API/AcheiUnB/__pycache__/urls.cpython-310.pyc
Binary file not shown.
Binary file removed API/AcheiUnB/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file removed API/AcheiUnB/__pycache__/wsgi.cpython-310.pyc
Binary file not shown.
Binary file removed API/AcheiUnB/__pycache__/wsgi.cpython-312.pyc
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Generated by Django 5.1.4 on 2025-01-08 21:10

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


class Migration(migrations.Migration):

dependencies = [
("chat", "0002_remove_message_chat_chatroom_message_room_and_more"),
("users", "0004_merge_20241229_1953"),
]

operations = [
migrations.RemoveField(
model_name="chatroom",
name="item_description",
),
migrations.AddField(
model_name="chatroom",
name="item",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="chatrooms",
to="users.item",
),
),
]
8 changes: 5 additions & 3 deletions API/chat/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.contrib.auth.models import User
from django.db import models

from users.models import Item


class ChatRoom(models.Model):
"""Representa uma sala de chat entre dois usuários."""
Expand All @@ -11,9 +13,9 @@ class ChatRoom(models.Model):
participant_2 = models.ForeignKey(
User, related_name="chatrooms_as_participant_2", on_delete=models.CASCADE
)
item_description = models.CharField(
max_length=255, blank=True, null=True
) # Descrição do item perdido (opcional)
item = models.ForeignKey(
Item, related_name="chatrooms", on_delete=models.CASCADE, null=True, blank=True
)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
Expand Down
19 changes: 17 additions & 2 deletions API/chat/serializers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from rest_framework import serializers

from users.models import Item
from .models import ChatRoom, Message


Expand All @@ -16,6 +16,8 @@ class ChatRoomSerializer(serializers.ModelSerializer):
messages = MessageSerializer(many=True, read_only=True)
participant_1_username = serializers.ReadOnlyField(source="participant_1.username")
participant_2_username = serializers.ReadOnlyField(source="participant_2.username")
item_id = serializers.IntegerField(write_only=True, required=True)
item_name = serializers.ReadOnlyField(source="item.name")

class Meta:
model = ChatRoom
Expand All @@ -25,7 +27,20 @@ class Meta:
"participant_1_username",
"participant_2",
"participant_2_username",
"item_description",
"item_id",
"item_name",
"created_at",
"messages",
]

def validate_item_id(self, value):
# Verifica se o item associado existe
if not Item.objects.filter(id=value).exists():
raise serializers.ValidationError("O item associado não foi encontrado.")
return value

def create(self, validated_data):
# Associa o item ao chat usando o item_id
item_id = validated_data.pop("item_id")
validated_data["item"] = Item.objects.get(id=item_id)
return super().create(validated_data)
33 changes: 24 additions & 9 deletions API/chat/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from django.db import models # Certifique-se de importar models para usar Q
from rest_framework.exceptions import ValidationError
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from users.models import Item

from chat.models import ChatRoom, Message

from .serializers import ChatRoomSerializer, MessageSerializer
Expand All @@ -16,17 +17,31 @@ class ChatRoomViewSet(ModelViewSet):
permission_classes = [IsAuthenticated]

def create(self, request, *args, **kwargs):
participant_1 = request.data.get("participant_1")
participant_2 = request.data.get("participant_2")
participant_1_id = request.data.get("participant_1")
participant_2_id = request.data.get("participant_2")
item_id = request.data.get("item_id")

# Verifica se todos os dados necessários foram fornecidos
if not participant_1_id or not participant_2_id or not item_id:
raise ValidationError(
"Os campos participant_1, participant_2 e item são obrigatórios."
)

# Verifica se o item existe
try:
item = Item.objects.get(id=item_id)
except Item.DoesNotExist:
raise ValidationError({"item": "Item não encontrado."})

# Verifica se a sala já existe
# Verifica se já existe um chat para este item e participantes
if ChatRoom.objects.filter(
(
models.Q(participant_1=participant_1, participant_2=participant_2)
| models.Q(participant_1=participant_2, participant_2=participant_1)
)
item=item,
participant_1__in=[participant_1_id, participant_2_id],
participant_2__in=[participant_1_id, participant_2_id],
).exists():
raise ValidationError("Já existe um chat entre esses participantes.")
raise ValidationError(
"Já existe um chat para este item com os mesmos participantes."
)

return super().create(request, *args, **kwargs)

Expand Down
Binary file removed API/users/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/admin.cpython-310.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/admin.cpython-312.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/apps.cpython-310.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/apps.cpython-312.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/models.cpython-310.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/models.cpython-312.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/views.cpython-310.pyc
Binary file not shown.
Binary file removed API/users/__pycache__/views.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

AcheiUnB é um projeto desenvolvido para facilitar a vida dos estudantes da Universidade de Brasília (UnB) na busca e recuperação de itens perdidos. A plataforma permite que os alunos registrem e encontrem objetos, facilitando o contato entre quem perdeu e encontrou o item. O objetivo é reduzir a dependência de grupos de mensagens e proporcionar um sistema mais organizado e acessível para achados e perdidos.


## 📝 Sumário

- [AcheiUnB](#acheiunb)
Expand Down

0 comments on commit f1f5c27

Please sign in to comment.