Skip to content

Commit

Permalink
Merge pull request #234 from unb-mds/228/front/colocar-filtro-e-valor…
Browse files Browse the repository at this point in the history
…es-estáticos-nos-selects

228/front/colocar filtro e valores estáticos nos selects
  • Loading branch information
anaelisaramos authored Feb 14, 2025
2 parents 9519a96 + cf1b0eb commit 8230d5b
Show file tree
Hide file tree
Showing 25 changed files with 2,109 additions and 371 deletions.
10 changes: 3 additions & 7 deletions API/AcheiUnB/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@
ROOT_URLCONF = "AcheiUnB.urls"

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"users.authentication.CookieJWTAuthentication",
),
"DEFAULT_AUTHENTICATION_CLASSES": ("users.authentication.CookieJWTAuthentication",),
"DEFAULT_RENDERER_CLASSES": [
"rest_framework.renderers.JSONRenderer",
],
Expand Down Expand Up @@ -174,7 +172,6 @@
]



LANGUAGE_CODE = "en-us"

TIME_ZONE = "America/Sao_Paulo"
Expand All @@ -187,11 +184,10 @@
CORS_ALLOW_CREDENTIALS = True



STATIC_URL = "/static/"

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "AcheiUnB/static/dist"),
os.path.join(BASE_DIR, "AcheiUnB/static/dist"),
]


Expand All @@ -213,7 +209,7 @@
CELERY_BEAT_SCHEDULE = {
"delete_old_items_and_chats": {
"task": "users.tasks.delete_old_items_and_chats",
"schedule": crontab(hour=3, minute=0),
"schedule": crontab(hour=3, minute=0),
},
}

Expand Down
Binary file not shown.
10 changes: 3 additions & 7 deletions API/AcheiUnB/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@


def vue_app(request):
return render(request, "index.html")
return render(request, "index.html")


urlpatterns = [
Expand All @@ -26,12 +26,8 @@ def vue_app(request):
name="microsoft_callback",
),
path("", vue_app, name="vue_home"),
path(
"api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"
),
path(
"api/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"
),
path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
path("api/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
path("api/chat/", include("chat.urls")),
path("api/", include("users.urls")),
path("delete-user/<int:user_id>/", DeleteUserView.as_view(), name="delete_user"),
Expand Down
2 changes: 1 addition & 1 deletion API/users/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ class UsersConfig(AppConfig):
name = "users"

def ready(self):
import users.signals
import users.signals
31 changes: 11 additions & 20 deletions API/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
profile_picture = models.URLField(
null=True, blank=True
)
profile_picture = models.URLField(null=True, blank=True)
welcome_email_sent = models.BooleanField(default=False)


class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=50, unique=True)
category_id = models.CharField(max_length=10, unique=True)

def __str__(self):
Expand All @@ -20,15 +18,16 @@ def __str__(self):

class Location(models.Model):
name = models.CharField(max_length=100, unique=True)
location_id = models.CharField(max_length=2, unique=True)
location_id = models.CharField(max_length=2, unique=True)

def __str__(self):
return self.name


class Color(models.Model):
name = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=50, unique=True)
color_id = models.CharField(max_length=2, unique=True)

def __str__(self):
return self.name

Expand All @@ -47,23 +46,15 @@ class Item(models.Model):
("lost", "Lost"),
]

user = models.ForeignKey(
User, on_delete=models.SET_NULL, null=True, blank=True
)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
name = models.CharField(max_length=100)
description = models.TextField(max_length=250, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True)
color = models.ForeignKey(
Color, on_delete=models.SET_NULL, null=True, blank=True
)
brand = models.ForeignKey(
Brand, on_delete=models.SET_NULL, null=True, blank=True
)
status = models.CharField(
max_length=10, choices=STATUS_CHOICES, default="lost"
)
found_lost_date = models.DateTimeField(null=True, blank=True)
color = models.ForeignKey(Color, on_delete=models.SET_NULL, null=True, blank=True)
brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True, blank=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="lost")
found_lost_date = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)

barcode = models.CharField(max_length=10, editable=False, blank=True)
Expand Down Expand Up @@ -91,7 +82,7 @@ def __str__(self):

class ItemImage(models.Model):
item = models.ForeignKey(Item, related_name="images", on_delete=models.CASCADE)
image_url = models.URLField()
image_url = models.URLField()

def __str__(self):
return f"Image for {self.item.name}"
4 changes: 2 additions & 2 deletions API/users/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@


class LostFoundPagination(PageNumberPagination):
page_size = 27
page_size_query_param = "page_size"
page_size = 27
page_size_query_param = "page_size"
4 changes: 2 additions & 2 deletions API/users/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class ItemSerializer(serializers.ModelSerializer):
image_urls = serializers.SerializerMethodField(read_only=True)
image_ids = serializers.SerializerMethodField(read_only=True)
user_id = serializers.IntegerField(source="user.id", read_only=True)
barcode = serializers.CharField(read_only=True)
barcode = serializers.CharField(read_only=True)
category_name = serializers.SerializerMethodField()
location_name = serializers.SerializerMethodField()
color_name = serializers.SerializerMethodField()
Expand Down Expand Up @@ -78,7 +78,7 @@ class Meta:
"images",
"remove_images",
"image_urls",
"image_ids",
"image_ids",
]

def validate_images(self, value):
Expand Down
2 changes: 1 addition & 1 deletion API/users/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def send_welcome_email_on_first_login(sender, request, user, **kwargs):
if not profile.welcome_email_sent:
print("Primeiro login detectado. Enviando e-mail de boas-vindas.")
send_welcome_email.delay(user.email, user.first_name)
profile.welcome_email_sent = True
profile.welcome_email_sent = True
profile.save()
else:
print("E-mail de boas-vindas já enviado anteriormente. Nenhuma ação tomada.")
Expand Down
3 changes: 2 additions & 1 deletion API/users/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def send_welcome_email(user_email, user_name):

@shared_task
def find_and_notify_matches_task(target_item_id, max_distance=2):
from .match import find_and_notify_matches
from .match import find_and_notify_matches

"""Task assíncrona para encontrar e notificar matches."""
try:
Expand Down Expand Up @@ -94,6 +94,7 @@ def upload_images_to_cloudinary(object_id, images, object_type="item"):
except Exception as e:
print(f"Erro ao fazer upload de imagem para o objeto {object_id}: {e}")


@shared_task
def remove_images_from_item(image_ids):
"""Remove imagens associadas a um item."""
Expand Down
39 changes: 15 additions & 24 deletions API/users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,14 @@ class UserListView(View):
def get(self, request, user_id=None):
if user_id:
user = get_object_or_404(User, id=user_id)
profile = getattr(user, "profile", None)
profile_picture = (
profile.profile_picture if profile else None
)
profile = getattr(user, "profile", None)
profile_picture = profile.profile_picture if profile else None

user_data = {
"id": user.id,
"first_name": user.first_name,
"email": user.email,
"foto": profile_picture,
"foto": profile_picture,
}
return JsonResponse(user_data, status=200)

Expand All @@ -60,9 +58,7 @@ def get(self, request, user_id=None):
"id": user.id,
"first_name": user.first_name,
"email": user.email,
"foto": getattr(
user.profile, "profile_picture", None
),
"foto": getattr(user.profile, "profile_picture", None),
}
for user in users
]
Expand Down Expand Up @@ -147,7 +143,8 @@ def perform_update(self, serializer):
)
self.schedule_match_task(item)

''' Estrutura de match para implementação futura

""" Estrutura de match para implementação futura
Match de itens caso o usuário queira ver os possíveis matches pelo site:
class MatchItemViewSet(APIView):
Expand All @@ -171,7 +168,7 @@ def get(self, request, item_id):
}
for match in matches
]
return Response(data, status=200)'''
return Response(data, status=200)"""


class MyItemsLostView(APIView):
Expand Down Expand Up @@ -291,9 +288,7 @@ class UserDetailView(APIView):

def get(self, request):
user = request.user
request.headers.get("Authorization", "").replace(
"Bearer ", ""
)
request.headers.get("Authorization", "").replace("Bearer ", "")
logger.info(f"Usuário autenticado: {user.username} (ID: {user.id})")

try:
Expand All @@ -311,7 +306,7 @@ def get(self, request):
"first_name": user.first_name,
"last_name": user.last_name,
"matricula": matricula,
"foto": foto_url,
"foto": foto_url,
}
return Response(user_data)

Expand Down Expand Up @@ -414,7 +409,7 @@ def microsoft_callback(request):
value=jwt_access,
httponly=True,
secure=True,
samesite="Strict",
samesite="Strict",
max_age=3600,
)
return response
Expand Down Expand Up @@ -448,7 +443,7 @@ def post(self, request):
"""
Testa a criação de um usuário completo no banco de dados.
"""
data = request.data
data = request.data

try:
user, created = User.objects.update_or_create(
Expand All @@ -457,9 +452,7 @@ def post(self, request):
"username": data.get("username"),
"first_name": data.get("first_name"),
"last_name": data.get("last_name"),
"password": data.get(
"password", ""
),
"password": data.get("password", ""),
"last_login": data.get("last_login", datetime.now()),
"is_superuser": data.get("is_superuser", False),
"is_staff": data.get("is_staff", False),
Expand Down Expand Up @@ -506,11 +499,9 @@ def get_user_photo(access_token):
url = "https://graph.microsoft.com/v1.0/me/photo/$value"
headers = {"Authorization": f"Bearer {access_token}"}

response = requests.get(
url, headers=headers, stream=True
)
response = requests.get(url, headers=headers, stream=True)
if response.status_code == 200:
return response.content
return response.content
else:
raise Exception(
f"Erro ao buscar a foto do usuário: {response.status_code} - {response.text}"
Expand All @@ -525,7 +516,7 @@ class DeleteUserView(View):
def delete(self, request, user_id):
try:
user = User.objects.get(id=user_id)
user.delete()
user.delete()
return JsonResponse(
{"message": f"Usuário com ID {user_id} foi deletado com sucesso."},
status=200,
Expand Down
Loading

0 comments on commit 8230d5b

Please sign in to comment.