Skip to content

Commit

Permalink
Merge: 모델 변경에 따른 코드 수정, timestamp필드사용 대신 basemodel상속으로 변경
Browse files Browse the repository at this point in the history
[Feature/notification] 모델 변경에 따른 코드 수정, timestamp필드사용 대신 basemodel상속으로 변경
  • Loading branch information
yyysolhhh authored May 25, 2024
2 parents f14dad5 + 5a32d32 commit 0457189
Show file tree
Hide file tree
Showing 9 changed files with 24 additions and 26 deletions.
2 changes: 1 addition & 1 deletion apps/chat/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class MessageAdmin(admin.ModelAdmin[Message]):
("Status", {"fields": ("status",)}),
)

list_display = ("chatroom", "sender", "text", "image", "status", "timestamp")
list_display = ("chatroom", "sender", "text", "image", "status", "updated_at", "created_at")
search_fields = ("text", "sender")
ordering = ("sender",)

Expand Down
2 changes: 1 addition & 1 deletion apps/chat/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ async def receive_json(self, content: dict[str, Any], **kwargs: Any) -> None:
"sender_id": self.scope["user"].id,
"chatroom_id": self.chatroom_id,
"status": True,
"timestamp": timezone.now().isoformat(),
"created_at": timezone.now().isoformat(),
}

# 수신한 데이터에서 이미지가 있으면 데이터에 포함
Expand Down
4 changes: 2 additions & 2 deletions apps/chat/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.db import models

from apps.common.models import BaseModel
from apps.common.utils import uuid4_generator
from apps.product.models import Product
from apps.user.models import Account
Expand All @@ -21,13 +22,12 @@ def __str__(self) -> str:
return f"판매자: {self.borrower.nickname}, 대여자: {self.lender.nickname}의 채팅방"


class Message(models.Model):
class Message(BaseModel):
chatroom = models.ForeignKey(Chatroom, on_delete=models.CASCADE)
sender = models.ForeignKey(Account, on_delete=models.CASCADE)
text = models.TextField()
image = models.ImageField(upload_to=upload_to_s3_chat, null=True, blank=True)
status = models.BooleanField(default=True) # 메시지의 읽음 여부를 처리
timestamp = models.DateTimeField(auto_now_add=True)

def __str__(self) -> str:
return f"{self.sender} : {self.text[:30]}.."
6 changes: 3 additions & 3 deletions apps/chat/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def test_로그인_유저의_채팅방리스트_가져오기_마지막_메시지
"sender_id": self.lender.id,
"chatroom_id": chatroom.id,
"status": True,
"timestamp": timezone.now().isoformat(),
"created_at": timezone.now().isoformat(),
"text": f"last chat message",
}
self.redis_conn.lpush(key, json.dumps(data))
Expand Down Expand Up @@ -135,7 +135,7 @@ def test_채팅에_참여한_유저가_get요청을_보낼때_redis에만_데이
"sender_id": self.user.id,
"chatroom_id": self.chatroom.id,
"status": True,
"timestamp": timezone.now().isoformat(),
"created_at": timezone.now().isoformat(),
}
for i in range(40):
data["text"] = f"test chat message - {i + 1}"
Expand All @@ -161,7 +161,7 @@ def test_채팅메시지가_db_redis에_분산되어_있는경우(self) -> None:
}
for i in range(40):
data["text"] = f"test chat message - {i + 1}"
data["timestamp"] = (timezone.now().isoformat(),)
data["created_at"] = (timezone.now().isoformat(),)
if i < 30:
Message.objects.create(**data)
else:
Expand Down
6 changes: 3 additions & 3 deletions apps/chat/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def get_last_message(chatroom_id: int) -> Optional[dict[str, Any]]:
if messages:
from apps.chat.serializers import MessageSerializer

return MessageSerializer(messages.order_by("-timestamp").first()).data
return MessageSerializer(messages.order_by("-created_at").first()).data

return None

Expand All @@ -167,7 +167,7 @@ def get_chatroom_message(chatroom_id: int) -> Any:
messages = [json.loads(msg) for msg in stored_messages]

# 데이터베이스에서 30 - stored_message_num을 뺀 개수만큼 가져옴
db_messages = Message.objects.filter(chatroom_id=chatroom_id).order_by("-timestamp")
db_messages = Message.objects.filter(chatroom_id=chatroom_id).order_by("-created_at")

# 디비에 저장된 메시지가 30-stored_message_num 보다 많으면 슬라이싱해서 필요한 만큼의 데이터를 가져옴
if db_messages.count() >= 30 - stored_message_num:
Expand All @@ -182,7 +182,7 @@ def get_chatroom_message(chatroom_id: int) -> Any:
db_messages = Message.objects.filter(chatroom_id=chatroom_id)
if db_messages:
if db_messages.count() >= 30:
serialized_messages = MessageSerializer(db_messages.order_by("-timestamp")[:30], many=True).data
serialized_messages = MessageSerializer(db_messages.order_by("-created_at")[:30], many=True).data
return serialized_messages

serialized_messages = MessageSerializer(db_messages, many=True).data
Expand Down
9 changes: 4 additions & 5 deletions apps/notification/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer

from apps.notification.models import GlobalNotification, GlobalNotificationConfirm
from apps.notification.utils import (
confirm_notification,
create_global_notification_confirm,
Expand Down Expand Up @@ -56,20 +55,20 @@ async def receive_json(self, content: dict[str, Any], **kwargs: Any) -> None:
async def global_notification_confirm(self, data: dict[str, Any]) -> None:
try:
await database_sync_to_async(confirm_notification)(
model=GlobalNotificationConfirm, user_id=self.user.id, notification_id=data["notification_id"]
command=data.get("command"), user_id=self.user.id, notification_id=data["notification_id"]
)
except Exception as e:
logger.error("예외 발생: %s", e, exc_info=True)
await self.close(1011, reason="알림 읽음 처리시 예외 발생")
await self.close(1011, reason="기타 알림 읽음 처리시 예외 발생")

async def rental_notification_confirm(self, data: dict[str, Any]) -> None:
try:
await database_sync_to_async(confirm_notification)(
model=GlobalNotification, user_id=self.user.id, notification_id=data["notification_id"]
command=data.get("command"), user_id=self.user.id, notification_id=data["notification_id"]
)
except Exception as e:
logger.error("예외 발생: %s", e, exc_info=True)
await self.close(1011, reason="알림 읽음 처리시 예외 발생")
await self.close(1011, reason="대여 알림 읽음 처리시 예외 발생")

async def chat_notification(self, event: dict[str, Any]) -> None:
try:
Expand Down
6 changes: 3 additions & 3 deletions apps/notification/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def to_representation(self, instance: GlobalNotificationConfirm) -> dict[str, An

class RentalNotificationSerializer(serializers.ModelSerializer[RentalNotification]):
product_name = serializers.CharField(source="rental_history.product.name") # 상품 이름
product_image = serializers.SerializerMethodField() # 상품 이미지
image = serializers.SerializerMethodField() # 상품 이미지
borrower = serializers.CharField(source="rental_history.borrower.nickname") # 빌리는 사람
lender = serializers.CharField(source="rental_history.product.lender.nickname") # 판매자
rental_date = serializers.DateTimeField(source="rental_history.rental_date") # 대여일
Expand All @@ -55,7 +55,7 @@ class Meta:
"id",
"recipient",
"product_name",
"product_image",
"image",
"borrower",
"lender",
"rental_date",
Expand All @@ -65,7 +65,7 @@ class Meta:
"text",
]

def get_product_image(self, obj: RentalNotification) -> Any:
def get_image(self, obj: RentalNotification) -> Any:
product_images: RentalNotification = obj.rental_history.product.images.first() # type: ignore
if product_images:
# 이미지의 URL을 리턴
Expand Down
3 changes: 1 addition & 2 deletions apps/notification/tests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import base64
import json

from datetime import datetime, timedelta

from channels.db import database_sync_to_async
Expand Down Expand Up @@ -102,7 +101,7 @@ async def test_RentalHistory가_처음_생성될때_알림메시지_테스트(se
req_notification = await communicator2.receive_json_from()

self.assertEqual(req_notification["product_name"], rental_history.product.name)
self.assertEqual(req_notification["product_image"], self.product_image.image.url)
self.assertEqual(req_notification["image"], self.product_image.image.url)
self.assertEqual(req_notification["borrower"], rental_history.borrower.nickname)
self.assertEqual(req_notification["lender"], rental_history.product.lender.nickname)
self.assertEqual(req_notification["type"], "rental_notification")
Expand Down
12 changes: 6 additions & 6 deletions apps/notification/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,14 @@ def get_chat_notification_group_name(chatroom_id: int) -> str:
# return other_values


def confirm_notification(model: models.Model, notification_id: int, user_id: int) -> None:
def confirm_notification(command: str, notification_id: int, user_id: int) -> None:
"""
유저가 확인한 알림을 가져와서 comfirm = True 로 변경
"""
if isinstance(model, RentalNotification):
model.objects.filter(id=notification_id, recipient_id=user_id).update(confirm=True)
if isinstance(model, GlobalNotificationConfirm):
model.objects.filter(notification_id=notification_id, user_id=user_id).update(confirm=True)
if command == "RentalNotificationConfirm":
RentalNotification.objects.filter(id=notification_id, recipient_id=user_id).update(confirm=True)
if command == "globalNotificationConfirm":
GlobalNotificationConfirm.objects.filter(notification_id=notification_id, user_id=user_id).update(confirm=True)


def create_rental_notification(
Expand Down Expand Up @@ -157,7 +157,7 @@ def get_unread_chat_notifications(user_id: int) -> list[ReturnDict[Any, Any]]:
unread_last_messages = []
if chatroom_list:
for chatroom in chatroom_list:
message = chatroom.message_set.exclude(sender=user_id).filter(status=True).order_by("-timestamp").first()
message = chatroom.message_set.exclude(sender=user_id).filter(status=True).order_by("-created_at").first()
if message:
data = MessageSerializer(message).data
data["type"] = "chat_notification"
Expand Down

0 comments on commit 0457189

Please sign in to comment.