Skip to content

Commit bc97576

Browse files
authored
Merge: 알림 확인 메서드 수정, 채팅 메시지 올바르게 내려주도록 변경
[Fix/notification-chat] 알림 확인 메서드 수정, 채팅 메시지 올바르게 내려주도록 변경
2 parents 3a00e2e + 97df8fa commit bc97576

File tree

4 files changed

+62
-27
lines changed

4 files changed

+62
-27
lines changed

apps/chat/tests.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,8 @@ def test_채팅에_참여한_유저가_get요청을_보낼때_redis에만_데이
146146

147147
self.assertEqual(response.status_code, status.HTTP_200_OK)
148148
self.assertEqual(len(response.data.get("messages")), 30)
149-
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 40")
150-
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 11")
149+
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 11")
150+
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 40")
151151
# 테스트가 끝나면 레디스의 자원을 정리
152152
self.redis_conn.delete(key)
153153

@@ -175,8 +175,8 @@ def test_채팅메시지가_db_redis에_분산되어_있는경우(self) -> None:
175175

176176
self.assertEqual(response.status_code, status.HTTP_200_OK)
177177
self.assertEqual(len(response.data.get("messages")), 30)
178-
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 40")
179-
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 11")
178+
self.assertEqual(response.data["messages"][0]["text"], "test chat message - 11")
179+
self.assertEqual(response.data["messages"][-1]["text"], "test chat message - 40")
180180

181181
# 테스트가 끝나면 레디스의 자원을 정리
182182
self.redis_conn.delete(key)

apps/chat/utils.py

+16-12
Original file line numberDiff line numberDiff line change
@@ -159,34 +159,38 @@ def get_chatroom_message(chatroom_id: int) -> Any:
159159
# 레디스에 저장된 메시지가 30개가 넘으면 가장 마지막에 저장된 메시지부터 30개를 가져옴
160160
if stored_message_num >= 30:
161161
stored_messages = redis_conn.lrange(key, 0, 29)
162-
messages = [json.loads(msg) for msg in reversed(stored_messages)]
162+
messages = [json.loads(msg) for msg in stored_messages[::-1]]
163163
return messages
164164

165165
# 30개가 넘지않으면 레디스에 저장된 메시지들을 가져오고
166-
stored_messages = redis_conn.lrange(key, 0, -1)
167-
messages = [json.loads(msg) for msg in reversed(stored_messages)]
166+
stored_messages = redis_conn.lrange(key, 0, stored_message_num)
167+
messages = [json.loads(msg) for msg in stored_messages[::-1]]
168168

169169
# 데이터베이스에서 30 - stored_message_num을 뺀 개수만큼 가져옴
170-
db_messages = Message.objects.filter(chatroom_id=chatroom_id).order_by("created_at")
170+
db_messages = Message.objects.filter(chatroom_id=chatroom_id).order_by("-created_at")
171+
172+
# db에 저장된 메시지가 없으면 레디스에 캐싱된 메시지만 가져옴
173+
if not db_messages.exists():
174+
return messages
171175

172176
# 디비에 저장된 메시지가 30-stored_message_num 보다 많으면 슬라이싱해서 필요한 만큼의 데이터를 가져옴
173-
if db_messages.count() >= 30 - stored_message_num:
177+
if len(db_messages) >= 30 - stored_message_num:
174178
serialized_messages = MessageSerializer(db_messages[: 30 - stored_message_num], many=True).data
175-
return serialized_messages + messages # type: ignore
179+
return serialized_messages[::-1] + messages
176180

177181
# 디비에 저장된 메시지가 30-stored_message_num 보다 적으면 db에 저장된 채팅방의 모든 메시지를 가져옴
178-
serialized_messages = MessageSerializer(db_messages.order_by("created_at"), many=True).data
179-
return serialized_messages + messages # type: ignore
182+
serialized_messages = MessageSerializer(db_messages, many=True).data
183+
return serialized_messages[::-1] + messages
180184

181185
# 레디스에 해당 채팅방 그룹 네임으로 지정된 키값이 없으면 데이터베이스에서 채팅 메시지를 가져옴
182186
db_messages = Message.objects.filter(chatroom_id=chatroom_id)
183187
if db_messages:
184188
if db_messages.count() >= 30:
185-
serialized_messages = MessageSerializer(db_messages.order_by("created_at")[:30], many=True).data
186-
return serialized_messages
189+
serialized_messages = MessageSerializer(db_messages[:30], many=True).data
190+
return serialized_messages[::-1]
187191

188-
serialized_messages = MessageSerializer(db_messages.order_by("created_at"), many=True).data
189-
return serialized_messages
192+
serialized_messages = MessageSerializer(db_messages, many=True).data
193+
return serialized_messages[::-1]
190194

191195
# 어디에도 데이터가 존재하지않으면 None을 반환
192196
return None

apps/notification/tests.py

+32-5
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@
1515
from apps.chat.models import Chatroom
1616
from apps.chat.utils import get_group_name
1717
from apps.notification.consumers import NotificationConsumer
18-
from apps.notification.models import GlobalNotification, GlobalNotificationConfirm
18+
from apps.notification.models import (
19+
GlobalNotification,
20+
GlobalNotificationConfirm,
21+
RentalNotification,
22+
)
1923
from apps.product.models import Product, ProductImage, RentalHistory
2024
from apps.user.models import Account
2125

@@ -109,6 +113,29 @@ async def test_RentalHistory가_처음_생성될때_알림메시지_테스트(se
109113
self.assertEqual(req_notification["return_date"], rental_history.return_date.isoformat())
110114
self.assertEqual(req_notification["rental_date"], rental_history.rental_date.isoformat())
111115

116+
# 대여 알림이 생성되었는지 테스트
117+
self.assertTrue(
118+
await database_sync_to_async(
119+
RentalNotification.objects.filter(
120+
recipient=self.lender, rental_history=rental_history, confirm=False
121+
).exists
122+
)()
123+
)
124+
125+
rental_notification = await database_sync_to_async(RentalNotification.objects.get)(
126+
recipient=self.lender, rental_history=rental_history, confirm=False
127+
)
128+
129+
# 알림읽기테스트
130+
await communicator2.send_json_to(
131+
{"command": "rental_notification_confirm", "notification_id": rental_notification.id}
132+
)
133+
updated_confirm = await database_sync_to_async(RentalNotification.objects.get)(
134+
rental_history=rental_history, recipient=self.lender
135+
)
136+
self.assertFalse(updated_confirm.confirm)
137+
138+
# 소켓 연결 해제
112139
await communicator1.disconnect()
113140
await communicator2.disconnect()
114141

@@ -240,16 +267,16 @@ async def test_모든_사용자에게_공통으로_적용되는_알림_테스트
240267
# 유저1의 알림 읽기 테스트
241268
await communicator1.send_json_to({"command": "global_notification_confirm", "notification_id": notification.id})
242269
user1_confirm_instance = await database_sync_to_async(GlobalNotificationConfirm.objects.get)(
243-
notification=notification, user=self.user1, confirm=False
270+
notification=notification, user=self.user1
244271
)
245272
self.assertFalse(user1_confirm_instance.confirm)
246273

247274
# 유저2의 알림 읽기 테스트
248275
await communicator1.send_json_to({"command": "global_notification_confirm", "notification_id": notification.id})
249-
user1_confirm_instance = await database_sync_to_async(GlobalNotificationConfirm.objects.get)(
250-
notification=notification, user=self.user1, confirm=False
276+
user2_confirm_instance = await database_sync_to_async(GlobalNotificationConfirm.objects.get)(
277+
notification=notification, user=self.user2
251278
)
252-
self.assertFalse(user1_confirm_instance.confirm)
279+
self.assertFalse(user2_confirm_instance.confirm)
253280

254281
# 소켓 정리
255282
await communicator1.disconnect()

apps/notification/utils.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,12 @@ def confirm_notification(command: str, notification_id: int, user_id: int) -> No
119119
"""
120120
유저가 확인한 알림을 가져와서 comfirm = True 로 변경
121121
"""
122-
if command == "RentalNotificationConfirm":
123-
RentalNotification.objects.filter(id=notification_id, recipient_id=user_id).update(confirm=True)
124-
if command == "globalNotificationConfirm":
125-
GlobalNotificationConfirm.objects.filter(notification_id=notification_id, user_id=user_id).update(confirm=True)
122+
if command == "rental_notification_confirm":
123+
RentalNotification.objects.filter(id=notification_id, recipient_id=user_id, confirm=False).update(confirm=True)
124+
if command == "global_notification_confirm":
125+
GlobalNotificationConfirm.objects.filter(
126+
notification_id=notification_id, user_id=user_id, confirm=False
127+
).update(confirm=True)
126128

127129

128130
def create_rental_notification(
@@ -167,9 +169,11 @@ def get_unread_chat_notifications(user_id: int) -> list[ReturnDict[Any, Any]]:
167169

168170
def get_unread_notifications(user_id: int) -> dict[str, Any]:
169171
result: dict[str, Any] = {}
170-
unread_global_notification = GlobalNotificationConfirm.objects.filter(user_id=user_id, confirm=False)
172+
unread_global_notification = GlobalNotification.objects.filter(
173+
globalnotificationconfirm__user_id=user_id, globalnotificationconfirm__confirm=False
174+
)
171175
if unread_global_notification:
172-
result["global_notification"] = serializers.GlobalNotificationConfirmSerializer(
176+
result["global_notification"] = serializers.GlobalNotificationSerializer(
173177
unread_global_notification, many=True
174178
).data
175179

0 commit comments

Comments
 (0)