Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add remove all messgaes #3671

Merged
merged 1 commit into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions _templates/provider/new/package.ejs.t
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

{
"name": "@novu/<%= name %>",
"version": "^0.12.0",
"version": "<%= version %>",
"description": "A <%= name %> wrapper for novu",
"main": "build/main/index.js",
"typings": "build/main/index.d.ts",
Expand Down Expand Up @@ -38,7 +38,7 @@
"pnpm": "^7.26.0"
},
"dependencies": {
"@novu/stateless": "^0.13.0"
"@novu/stateless": "<%= version %>"
},
"devDependencies": {
"@istanbuljs/nyc-config-typescript": "~1.0.1",
Expand Down
5 changes: 3 additions & 2 deletions _templates/provider/new/src/lib/provider.ejs.t
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from '@novu/stateless';

export class <%= PascalName %><%= PascalType %>Provider implements I<%= PascalType %>Provider {
id = '<%= name %>';
channelType = ChannelTypeEnum.<%= UpperType %> as ChannelTypeEnum.<%= UpperType %>;

constructor(
Expand All @@ -28,8 +29,8 @@ export class <%= PascalName %><%= PascalType %>Provider implements I<%= PascalTy


return {
id: 'PLACEHOLDER',
date: 'PLACEHOLDER'
id: 'id_returned_by_provider',
date: 'current_time'
};
}
}
11 changes: 11 additions & 0 deletions apps/api/src/app/widgets/dtos/remove-all-messages.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsMongoId } from 'class-validator';

export class RemoveAllMessagesDto {
@ApiPropertyOptional({
description: 'FeedId to remove messages from',
})
@IsMongoId({ message: 'FeedId must be a valid MongoDB ObjectId' })
@IsOptional()
feedId: string;
}
108 changes: 108 additions & 0 deletions apps/api/src/app/widgets/e2e/remove-all-messages.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import axios from 'axios';
import { MessageRepository, NotificationTemplateEntity, SubscriberRepository } from '@novu/dal';
import { UserSession } from '@novu/testing';
import { expect } from 'chai';
import { ChannelTypeEnum } from '@novu/shared';

describe('Remove all messages - /widgets/messages (DELETE)', function () {
const messageRepository = new MessageRepository();
let session: UserSession;
let template: NotificationTemplateEntity;
let subscriberId: string;
let subscriberToken: string;
let subscriberProfile: {
_id: string;
} | null = null;

beforeEach(async () => {
session = new UserSession();
await session.initialize();
subscriberId = SubscriberRepository.createObjectId();

template = await session.createTemplate({
noFeedId: true,
});

const { body } = await session.testAgent
.post('/v1/widgets/session/initialize')
.send({
applicationIdentifier: session.environment.identifier,
subscriberId,
firstName: 'Test',
lastName: 'User',
email: 'test@example.com',
})
.expect(201);

const { token, profile } = body.data;

subscriberToken = token;
subscriberProfile = profile;
});

it('should remove all messages', async function () {
await session.triggerEvent(template.triggers[0].identifier, subscriberId);
await session.triggerEvent(template.triggers[0].identifier, subscriberId);
await session.triggerEvent(template.triggers[0].identifier, subscriberId);

await session.awaitRunningJobs(template._id);

const messagesBefore = await messageRepository.find({
_environmentId: session.environment._id,
_subscriberId: subscriberProfile?._id,
channel: ChannelTypeEnum.IN_APP,
});

expect(messagesBefore.length).to.equal(3);
await axios.delete(`http://localhost:${process.env.PORT}/v1/widgets/messages`, {
headers: {
Authorization: `Bearer ${subscriberToken}`,
},
});

const messagesAfter = await messageRepository.find({
_environmentId: session.environment._id,
_subscriberId: subscriberProfile?._id,
channel: ChannelTypeEnum.IN_APP,
});

expect(messagesAfter.length).to.equal(0);
});

it('should remove all messages of a specific feed', async function () {
const templateWithFeed = await session.createTemplate({ noFeedId: false });

const _feedId = templateWithFeed?.steps[0]?.template?._feedId;

await session.triggerEvent(template.triggers[0].identifier, subscriberId);
await session.triggerEvent(template.triggers[0].identifier, subscriberId);
await session.triggerEvent(template.triggers[0].identifier, subscriberId);
await session.triggerEvent(templateWithFeed.triggers[0].identifier, subscriberId);
await session.triggerEvent(templateWithFeed.triggers[0].identifier, subscriberId);

await session.awaitRunningJobs(templateWithFeed._id);
await session.awaitRunningJobs(template._id);

const messagesBefore = await messageRepository.find({
_environmentId: session.environment._id,
_subscriberId: subscriberProfile?._id,
channel: ChannelTypeEnum.IN_APP,
});

expect(messagesBefore.length).to.equal(5);

await axios.delete(`http://localhost:${process.env.PORT}/v1/widgets/messages?feedId=${_feedId}`, {
headers: {
Authorization: `Bearer ${subscriberToken}`,
},
});

const messagesAfter = await messageRepository.find({
_environmentId: session.environment._id,
_subscriberId: subscriberProfile?._id,
channel: ChannelTypeEnum.IN_APP,
});

expect(messagesAfter.length).to.equal(3);
});
});
2 changes: 2 additions & 0 deletions apps/api/src/app/widgets/usecases/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { UpdateMessageActions } from './mark-action-as-done/update-message-actio
import { GetFeedCount } from './get-feed-count/get-feed-count.usecase';
import { RemoveMessage } from './remove-message/remove-message.usecase';
import { MarkAllMessagesAs } from './mark-all-messages-as/mark-all-messages-as.usecase';
import { RemoveAllMessages } from './remove-messages/remove-all-messages.usecase';

export const USE_CASES = [
GetOrganizationData,
Expand All @@ -15,6 +16,7 @@ export const USE_CASES = [
GetNotificationsFeed,
InitializeSession,
RemoveMessage,
RemoveAllMessages,
MarkAllMessagesAs,
//
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { IsOptional, IsString } from 'class-validator';
import { EnvironmentWithSubscriber } from '../../../shared/commands/project.command';

export class RemoveAllMessagesCommand extends EnvironmentWithSubscriber {
@IsString()
@IsOptional()
feedId?: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import {
MessageEntity,
DalException,
MessageRepository,
SubscriberRepository,
SubscriberEntity,
MemberRepository,
FeedRepository,
FeedEntity,
} from '@novu/dal';
import { ChannelTypeEnum } from '@novu/shared';
import {
WsQueueService,
AnalyticsService,
InvalidateCacheService,
buildFeedKey,
buildMessageCountKey,
} from '@novu/application-generic';

import { RemoveAllMessagesCommand } from './remove-all-messages.command';
import { ApiException } from '../../../shared/exceptions/api.exception';
import { MarkEnum } from '../mark-message-as/mark-message-as.command';

@Injectable()
export class RemoveAllMessages {
constructor(
private invalidateCache: InvalidateCacheService,
private messageRepository: MessageRepository,
private wsQueueService: WsQueueService,
private analyticsService: AnalyticsService,
private subscriberRepository: SubscriberRepository,
private memberRepository: MemberRepository,
private feedRepository: FeedRepository
) {}

async execute(command: RemoveAllMessagesCommand): Promise<void> {
const subscriber = await this.subscriberRepository.findBySubscriberId(command.environmentId, command.subscriberId);
if (!subscriber) throw new NotFoundException(`Subscriber ${command.subscriberId} not found`);

try {
let feed;
if (command.feedId) {
feed = await this.feedRepository.findById(command.feedId);
if (!feed) {
throw new NotFoundException(`Feed with ${command.feedId} not found`);
}
}

const deleteMessageQuery: Partial<MessageEntity> = {
_environmentId: command.environmentId,
_organizationId: command.organizationId,
_subscriberId: subscriber._id,
channel: ChannelTypeEnum.IN_APP,
};

if (feed) {
deleteMessageQuery._feedId = feed._id;
}

await this.messageRepository.deleteMany(deleteMessageQuery);

await this.updateServices(command, subscriber, MarkEnum.SEEN, feed);
await this.updateServices(command, subscriber, MarkEnum.READ, feed);

const admin = await this.memberRepository.getOrganizationAdminAccount(command.organizationId);
if (admin) {
this.analyticsService.track(`Removed All Feed Messages - [Notification Center]`, admin._userId, {
_subscriber: subscriber._id,
_organization: command.organizationId,
_environment: command.environmentId,
_feedId: command.feedId,
});
}

await this.invalidateCache.invalidateQuery({
key: buildFeedKey().invalidate({
subscriberId: command.subscriberId,
_environmentId: command.environmentId,
}),
});

await this.invalidateCache.invalidateQuery({
key: buildMessageCountKey().invalidate({
subscriberId: command.subscriberId,
_environmentId: command.environmentId,
}),
});
} catch (e) {
if (e instanceof DalException) {
throw new ApiException(e.message);
}
throw e;
}
}

private async updateServices(command: RemoveAllMessagesCommand, subscriber, marked: string, feed?: FeedEntity) {
let count = 0;
if (feed) {
count = await this.messageRepository.getCount(
command.environmentId,
subscriber._id,
ChannelTypeEnum.IN_APP,
{
[marked]: false,
},
{ limit: 1000 }
);
}
this.updateSocketCount(subscriber, count, marked);
}

private updateSocketCount(subscriber: SubscriberEntity, count: number, mark: string) {
const eventMessage = `un${mark}_count_changed`;
const countKey = `un${mark}Count`;

this.wsQueueService.bullMqService.add(
'sendMessage',
{
event: eventMessage,
userId: subscriber._id,
payload: {
[countKey]: count,
},
},
{},
subscriber._organizationId
);
}
}
29 changes: 28 additions & 1 deletion apps/api/src/app/widgets/widgets.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ import {
DefaultValuePipe,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiExcludeController, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { ApiExcludeController, ApiNoContentResponse, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { AnalyticsService, GetSubscriberPreference, GetSubscriberPreferenceCommand } from '@novu/application-generic';
import { MessageEntity, SubscriberEntity } from '@novu/dal';
import { ButtonTypeEnum, MessageActionStatusEnum } from '@novu/shared';
Expand Down Expand Up @@ -49,6 +51,9 @@ import { MarkAllMessagesAsCommand } from './usecases/mark-all-messages-as/mark-a
import { MarkAllMessagesAs } from './usecases/mark-all-messages-as/mark-all-messages-as.usecase';
import { GetNotificationsFeedDto } from './dtos/get-notifications-feed-request.dto';
import { LimitPipe } from './pipes/limit-pipe/limit-pipe';
import { RemoveAllMessagesCommand } from './usecases/remove-messages/remove-all-messages.command';
import { RemoveAllMessages } from './usecases/remove-messages/remove-all-messages.usecase';
import { RemoveAllMessagesDto } from './dtos/remove-all-messages.dto';

@Controller('/widgets')
@ApiExcludeController()
Expand All @@ -59,6 +64,7 @@ export class WidgetsController {
private getFeedCountUsecase: GetFeedCount,
private markMessageAsUsecase: MarkMessageAs,
private removeMessageUsecase: RemoveMessage,
private removeAllMessagesUsecase: RemoveAllMessages,
private updateMessageActionsUsecase: UpdateMessageActions,
private getOrganizationUsecase: GetOrganizationData,
private getSubscriberPreferenceUsecase: GetSubscriberPreference,
Expand Down Expand Up @@ -228,6 +234,27 @@ export class WidgetsController {
return await this.removeMessageUsecase.execute(command);
}

@ApiOperation({
summary: `Remove a subscriber's feed messages`,
})
@UseGuards(AuthGuard('subscriberJwt'))
@Delete('/messages')
@ApiNoContentResponse({ description: 'Messages removed' })
@HttpCode(HttpStatus.NO_CONTENT)
async removeAllMessages(
@SubscriberSession() subscriberSession: SubscriberEntity,
@Query() query: RemoveAllMessagesDto
): Promise<void> {
const command = RemoveAllMessagesCommand.create({
organizationId: subscriberSession._organizationId,
subscriberId: subscriberSession.subscriberId,
environmentId: subscriberSession._environmentId,
feedId: query.feedId,
});

await this.removeAllMessagesUsecase.execute(command);
}

@ApiOperation({
summary: "Mark subscriber's all unread messages as read",
})
Expand Down
Loading
Loading