From a68cd4c7d3ae3642898aaa7b9d882ebadfb523c7 Mon Sep 17 00:00:00 2001 From: pradeepkumar Date: Thu, 19 Mar 2026 09:33:06 +0530 Subject: [PATCH] feat: Add endpoint and service logic to clear all messages within a conversation. --- src/messages/messages.controller.ts | 15 ++++++++++ src/messages/messages.service.ts | 43 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/messages/messages.controller.ts b/src/messages/messages.controller.ts index b2aa024..fb3f208 100644 --- a/src/messages/messages.controller.ts +++ b/src/messages/messages.controller.ts @@ -218,6 +218,21 @@ export class MessagesController { return this.messagesService.markMessagesAsRead(conversationId, userId); } + // ========================================== + // CLEAR CHAT (delete messages, keep conversation) + // ========================================== + @Delete('conversations/:id/messages') + @HttpCode(HttpStatus.OK) + @ApiOperation({ summary: 'Clear all messages in a conversation' }) + @ApiParam({ name: 'id', description: 'Conversation ID' }) + @ApiResponse({ status: 200, description: 'Messages cleared' }) + async clearChat( + @Param('id') conversationId: string, + @CurrentUser('id') userId: string, + ) { + return this.messagesService.clearChat(conversationId, userId); + } + // ========================================== // DELETE CONVERSATION // ========================================== diff --git a/src/messages/messages.service.ts b/src/messages/messages.service.ts index a3f15bb..048b613 100644 --- a/src/messages/messages.service.ts +++ b/src/messages/messages.service.ts @@ -615,6 +615,49 @@ export class MessagesService { }; } + /** + * Clear all messages in a conversation (keep the conversation itself) + */ + async clearChat(conversationId: string, userId: string) { + const conversation = await this.prisma.conversation.findUnique({ + where: { id: conversationId }, + include: { + agentProfile: { + select: { userId: true }, + }, + }, + }); + + if (!conversation) { + throw new NotFoundException('Conversation not found'); + } + + const isUser = conversation.userId === userId; + const isAgent = conversation.agentProfile.userId === userId; + + if (!isUser && !isAgent) { + throw new ForbiddenException('You are not part of this conversation'); + } + + // Delete all messages + await this.prisma.message.deleteMany({ + where: { conversationId }, + }); + + // Reset conversation preview + await this.prisma.conversation.update({ + where: { id: conversationId }, + data: { + lastMessageAt: null, + lastMessageText: null, + userUnreadCount: 0, + agentUnreadCount: 0, + }, + }); + + return null; + } + /** * Delete a conversation and all its messages */