Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 7x 7x 13x 2x 13x 2x 13x 2x 13x 13x 13x 1x 13x 13x 1x 1x 13x 7x 7x 13x 2x 13x 2x 13x 2x 13x 1x 13x 13x 1x | import { ForbiddenException, Injectable, Logger } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { paginate, type IPaginationOptions } from 'nestjs-typeorm-paginate';
import { LessThan, Repository } from 'typeorm';
import { globalConfiguration, Notification, type Company, type User } from '@amalia/core/models';
import { NotificationsTypes, toPaginatedResponse } from '@amalia/core/types';
import { PaginatedResponse } from '@amalia/core-http-types';
import { MessageTasks, MessageType, QueueService } from '@amalia/kernel/queue/core';
import { MailTemplate, SendMailCommand } from '@amalia/kernel/user-notifications/mail/events';
import { SlackClient } from '@amalia/kernel/user-notifications/slack/core';
import { CompaniesIntegrationsService } from '@amalia/tenants/companies/core';
import { AppUsersRepository } from '@amalia/tenants/users/core';
import { UserStatus } from '@amalia/tenants/users/types';
import { type NotificationDeliveryTask } from './notifications.types';
@Injectable()
export class NotificationService {
private readonly logger = new Logger(NotificationService.name);
public constructor(
private readonly companyIntegrationService: CompaniesIntegrationsService,
@InjectRepository(Notification) private readonly notificationRepository: Repository<Notification>,
private readonly commandBus: CommandBus,
private readonly appUsersRepository: AppUsersRepository,
private readonly queueService: QueueService,
) {}
/**
* Send email for notification
* @param email email address to send notification
* @param notificationText notification text
* @param notificationLink
* @param template
*/
private async sendEmailNotification(
user: User,
notificationText: string,
notificationLink?: string | null,
template: MailTemplate = MailTemplate.NOTIFICATION,
) {
const templateParams = {
URL: globalConfiguration().domain,
notificationText,
notificationLink,
};
await this.commandBus.execute(
new SendMailCommand({
recipient: user.email,
locale: user.language,
template,
templateParams,
}),
);
}
private async sendSlackNotification(
company: Company,
email: string,
notificationText: string,
notificationLink?: string | null,
) {
const user = await this.appUsersRepository.findUserByEmail(email);
if (!user) {
throw new ForbiddenException();
}
const slackAccessToken = await this.companyIntegrationService.getSlackAccessToken(company.id);
if (!slackAccessToken) {
this.logger.warn('Cannot send slack notification, team id not set');
return;
}
const slackClient = new SlackClient(slackAccessToken);
const [slackUser] = await slackClient.getUsersByEmail([user.email]);
if (!slackUser) {
this.logger.warn(`Cannot send slack notification, user ${user.email} not found in workspace`);
return;
}
const notificationContent = `${notificationText}${
notificationLink ? `\n<${notificationLink}|Click here for details>` : ''
}`;
await slackClient.postMessage({
channel: slackUser.id!,
text: notificationContent,
});
}
/**
* Something just happened. Send the notification to the message queue, it will be stored and
* delivered by the worker.
*/
public async scheduleNotificationDelivery(notificationDelivery: NotificationDeliveryTask) {
await this.queueService.sendToQueue(
{
type: MessageType.TASK,
taskIdentifier: MessageTasks.DELIVER_NOTIFICATION,
},
{ notificationDelivery },
);
}
/**
* Called on a new message. Stores the notification in database and deliver it to the user.
*
* @param companyId
* @param receiverUserId
* @param type
* @param content
* @param contentMetadata
* @param specificContentForEmail
* @param link
* @param authorUserId
* @param payload
* @param overrideTemplate
*/
public async deliverNotification({
companyId,
receiverUserId,
type,
content,
contentMetadata,
specificContentForEmail,
link,
authorUserId,
payload,
template,
}: NotificationDeliveryTask) {
const user = await this.appUsersRepository.findOne({ id: companyId } as Company, receiverUserId);
// Persist the notification in the database.
const notification = this.notificationRepository.create({
type,
content,
contentMetadata,
link,
user: { id: receiverUserId } as User,
company: { id: companyId } as Company,
author: { id: authorUserId } as User,
read: false,
payload,
});
await this.notificationRepository.save(notification);
// Deliver it to user via email.
if (this.shouldDeliverNotificationByEmail(user, notification)) {
await this.sendEmailNotification(user, specificContentForEmail ?? content, link, template);
}
if (this.shouldDeliverNotificationBySlack(user, notification)) {
await this.sendSlackNotification(user.company, user.email, content, link);
}
}
/**
* Paginates the list of a user's notifications.
*
* @param user
* @param company
* @param options
*/
public async listUserNotifications(
user: User,
company: Company,
options: IPaginationOptions,
): Promise<PaginatedResponse<Notification>> {
return paginate<Notification>(this.notificationRepository, options, {
where: {
company: { id: company.id },
user: { id: user.id },
},
order: { createdAt: 'DESC' },
}).then(toPaginatedResponse);
}
/**
* Count unread notifications for a user.
*
* @param user
* @param company
*/
public async countUnreadNotifications(user: User, company: Company): Promise<number> {
return this.notificationRepository.countBy({
user: { id: user.id },
company: { id: company.id },
read: false,
});
}
public async markAllNotificationsAsRead(user: User, company: Company, lastCheck: Date) {
await this.notificationRepository.update(
{
user: { id: user.id },
company: { id: company.id },
createdAt: LessThan(lastCheck),
},
{ read: true },
);
}
public shouldDeliverNotificationByEmail(user: User, notification: Notification): boolean {
if ([UserStatus.DEACTIVATED, UserStatus.INACTIVE].includes(user.status)) return false;
switch (notification.type) {
case NotificationsTypes.NEW_COMMENT_ON_STATEMENT:
return !!user.settings?.isReceiveEmailsOnNewComment;
case NotificationsTypes.NEW_EXPORT_AVAILABLE:
return !!user.settings?.isReceiveEmailsOnNewExport;
case NotificationsTypes.REVIEW_STATEMENT:
return user.settings?.isReceiveEmailsOnReview !== false;
case NotificationsTypes.NEW_PLAN_AGREEMENT:
return !!user.settings?.isReceiveEmailsOnPlanAgreementToConfirm;
case NotificationsTypes.DASHBOARD_SHARED:
return !!user.settings?.isReceiveEmailsOnDashboardShared;
default:
return false;
}
}
public shouldDeliverNotificationBySlack(user: User, notification: Notification): boolean {
if ([UserStatus.DEACTIVATED, UserStatus.INACTIVE].includes(user.status)) return false;
switch (notification.type) {
case NotificationsTypes.NEW_COMMENT_ON_STATEMENT:
return !!user.settings?.isReceiveSlacksOnNewComment;
case NotificationsTypes.NEW_EXPORT_AVAILABLE:
return !!user.settings?.isReceiveSlacksOnNewExport;
case NotificationsTypes.REVIEW_STATEMENT:
return user.settings?.isReceiveSlacksOnReview !== false;
default:
return false;
}
}
}
|