diff --git a/src/notifications/notifications.service.ts b/src/notifications/notifications.service.ts index e849909..1c8d9bc 100644 --- a/src/notifications/notifications.service.ts +++ b/src/notifications/notifications.service.ts @@ -108,6 +108,34 @@ export class NotificationsService implements OnModuleInit { token: string, device: string = 'web', ): Promise { + // First, remove this token from ALL other users to prevent cross-user notifications + // This handles the case where the same device switches between accounts + const allUsersWithToken = await this.prisma.user.findMany({ + where: { + id: { not: userId }, + fcmTokens: { not: Prisma.JsonNull }, + }, + select: { id: true, fcmTokens: true }, + }); + + for (const otherUser of allUsersWithToken) { + const otherTokens = this.parseFcmTokens(otherUser.fcmTokens); + const hasToken = otherTokens.some((t) => t.token === token); + if (hasToken) { + const cleaned = otherTokens.filter((t) => t.token !== token); + await this.prisma.user.update({ + where: { id: otherUser.id }, + data: { + fcmTokens: cleaned.length > 0 + ? (cleaned as unknown as Prisma.InputJsonValue) + : Prisma.JsonNull, + }, + }); + this.logger.log(`Removed FCM token from previous user ${otherUser.id}`); + } + } + + // Now register the token for the current user const user = await this.prisma.user.findUnique({ where: { id: userId }, select: { fcmTokens: true },