mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2026-03-10 18:41:46 +00:00
Compare commits
16 Commits
feature/ky
...
45acf73a4a
| Author | SHA1 | Date | |
|---|---|---|---|
| 45acf73a4a | |||
| d3ff755439 | |||
| 21653efc46 | |||
| 63b0a42eca | |||
| b1cda5e7dc | |||
| 2c8de913f8 | |||
| 170aa903c7 | |||
| 2f74aa36a9 | |||
| 2562515574 | |||
| 93b509b256 | |||
| 9c93a35093 | |||
| d77d59a793 | |||
| 83787c7c67 | |||
| a3cdf50cb7 | |||
| 0fb76d712d | |||
| ce1f6341b7 |
@ -1,5 +1,5 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEmail, IsString } from 'class-validator';
|
||||
import { IsEmail, IsOptional, IsString } from 'class-validator';
|
||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||
export class JuniorLoginRequestDto {
|
||||
@ApiProperty({ example: 'test@junior.com' })
|
||||
@ -9,4 +9,18 @@ export class JuniorLoginRequestDto {
|
||||
@ApiProperty({ example: 'Abcd1234@' })
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
||||
password!: string;
|
||||
|
||||
@ApiProperty({ example: 'device-123', description: 'Unique device identifier', required: false })
|
||||
@IsOptional()
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.deviceId' }) })
|
||||
deviceId?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'cXYzABC:APA91bHunvwY7rKpn8N7y6vDxS0qmQ5RZx2C8K...',
|
||||
description: 'Firebase Cloud Messaging token for push notifications',
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.fcmToken' }) })
|
||||
fcmToken?: string;
|
||||
}
|
||||
|
||||
@ -21,4 +21,18 @@ export class LoginRequestDto {
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
||||
@ValidateIf((o) => o.grantType === GrantType.PASSWORD)
|
||||
password!: string;
|
||||
|
||||
@ApiProperty({ example: 'device-123', description: 'Unique device identifier', required: false })
|
||||
@IsOptional()
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.deviceId' }) })
|
||||
deviceId?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'cXYzABC:APA91bHunvwY7rKpn8N7y6vDxS0qmQ5RZx2C8K...',
|
||||
description: 'Firebase Cloud Messaging token for push notifications',
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.fcmToken' }) })
|
||||
fcmToken?: string;
|
||||
}
|
||||
|
||||
@ -101,4 +101,18 @@ export class VerifyUserRequestDto {
|
||||
message: i18n('validation.MinLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
|
||||
})
|
||||
otp!: string;
|
||||
|
||||
@ApiProperty({ example: 'device-123', description: 'Unique device identifier', required: false })
|
||||
@IsOptional()
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.deviceId' }) })
|
||||
deviceId?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'cXYzABC:APA91bHunvwY7rKpn8N7y6vDxS0qmQ5RZx2C8K...',
|
||||
description: 'Firebase Cloud Messaging token for push notifications',
|
||||
required: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.fcmToken' }) })
|
||||
fcmToken?: string;
|
||||
}
|
||||
|
||||
@ -86,6 +86,12 @@ export class AuthService {
|
||||
|
||||
const tokens = await this.generateAuthToken(user);
|
||||
this.logger.log(`User with phone number ${user.fullPhoneNumber} verified successfully`);
|
||||
|
||||
// Register/update device with FCM token if provided
|
||||
if (verifyUserDto.fcmToken && verifyUserDto.deviceId) {
|
||||
await this.registerDeviceToken(user.id, verifyUserDto.deviceId, verifyUserDto.fcmToken);
|
||||
}
|
||||
|
||||
return [tokens, user];
|
||||
}
|
||||
|
||||
@ -271,6 +277,12 @@ export class AuthService {
|
||||
|
||||
const tokens = await this.generateAuthToken(user);
|
||||
this.logger.log(`Password validated successfully for user`);
|
||||
|
||||
// Register/update device with FCM token if provided
|
||||
if (loginDto.fcmToken && loginDto.deviceId) {
|
||||
await this.registerDeviceToken(user.id, loginDto.deviceId, loginDto.fcmToken);
|
||||
}
|
||||
|
||||
return [tokens, user];
|
||||
}
|
||||
|
||||
@ -291,9 +303,73 @@ export class AuthService {
|
||||
|
||||
const tokens = await this.generateAuthToken(user);
|
||||
this.logger.log(`Password validated successfully for user`);
|
||||
|
||||
// Register/update device with FCM token if provided
|
||||
if (juniorLoginDto.fcmToken && juniorLoginDto.deviceId) {
|
||||
await this.registerDeviceToken(user.id, juniorLoginDto.deviceId, juniorLoginDto.fcmToken);
|
||||
}
|
||||
|
||||
return [tokens, user];
|
||||
}
|
||||
|
||||
/**
|
||||
* Register or update device with FCM token
|
||||
* This method handles:
|
||||
* 1. Device already exists for this user → Update FCM token
|
||||
* 2. Device exists for different user → Transfer device to new user
|
||||
* 3. Device doesn't exist → Create new device
|
||||
*/
|
||||
private async registerDeviceToken(userId: string, deviceId: string, fcmToken: string): Promise<void> {
|
||||
try {
|
||||
this.logger.log(`Registering/updating device ${deviceId} with FCM token for user ${userId}`);
|
||||
|
||||
// Step 1: Check if device already exists for this user
|
||||
const existingDeviceForUser = await this.deviceService.findUserDeviceById(deviceId, userId);
|
||||
|
||||
if (existingDeviceForUser) {
|
||||
// Device exists for this user → Update FCM token and last access time
|
||||
await this.deviceService.updateDevice(deviceId, {
|
||||
fcmToken,
|
||||
userId,
|
||||
lastAccessOn: new Date(),
|
||||
});
|
||||
this.logger.log(`Device ${deviceId} updated with new FCM token for user ${userId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 2: Check if device exists for any user (different user scenario)
|
||||
const existingDevice = await this.deviceService.findByDeviceId(deviceId);
|
||||
|
||||
if (existingDevice) {
|
||||
// Device exists for different user → Transfer device to new user
|
||||
this.logger.log(
|
||||
`Device ${deviceId} exists for user ${existingDevice.userId}, transferring to user ${userId}`
|
||||
);
|
||||
await this.deviceService.updateDevice(deviceId, {
|
||||
userId,
|
||||
fcmToken,
|
||||
lastAccessOn: new Date(),
|
||||
});
|
||||
this.logger.log(`Device ${deviceId} transferred from user ${existingDevice.userId} to user ${userId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 3: Device doesn't exist → Create new device
|
||||
await this.deviceService.createDevice({
|
||||
deviceId,
|
||||
userId,
|
||||
fcmToken,
|
||||
lastAccessOn: new Date(),
|
||||
});
|
||||
this.logger.log(`New device ${deviceId} registered with FCM token for user ${userId}`);
|
||||
} catch (error) {
|
||||
// Log error but don't fail the login/signup process
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const errorStack = error instanceof Error ? error.stack : undefined;
|
||||
this.logger.error(`Failed to register device token for user ${userId}: ${errorMessage}`, errorStack);
|
||||
}
|
||||
}
|
||||
|
||||
private async generateAuthToken(user: User) {
|
||||
this.logger.log(`Generating auth token for user with id ${user.id}`);
|
||||
const [accessToken, refreshToken] = await Promise.all([
|
||||
|
||||
@ -42,7 +42,18 @@ export class CardRepository {
|
||||
}
|
||||
|
||||
getCardById(id: string): Promise<Card | null> {
|
||||
return this.cardRepository.findOne({ where: { id }, relations: ['account'] });
|
||||
return this.cardRepository.findOne({
|
||||
where: { id },
|
||||
relations: [
|
||||
'account',
|
||||
'customer',
|
||||
'customer.user',
|
||||
'customer.junior',
|
||||
'customer.junior.guardian',
|
||||
'customer.junior.guardian.customer',
|
||||
'customer.junior.guardian.customer.user',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
findCardByChildId(guardianId: string, childId: string): Promise<Card | null> {
|
||||
@ -59,14 +70,30 @@ export class CardRepository {
|
||||
getCardByVpan(vpan: string): Promise<Card | null> {
|
||||
return this.cardRepository.findOne({
|
||||
where: { vpan },
|
||||
relations: ['account'],
|
||||
relations: [
|
||||
'account',
|
||||
'customer',
|
||||
'customer.user',
|
||||
'customer.junior',
|
||||
'customer.junior.guardian',
|
||||
'customer.junior.guardian.customer',
|
||||
'customer.junior.guardian.customer.user',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
getCardByCustomerId(customerId: string): Promise<Card | null> {
|
||||
return this.cardRepository.findOne({
|
||||
where: { customerId },
|
||||
relations: ['account'],
|
||||
relations: [
|
||||
'account',
|
||||
'customer',
|
||||
'customer.user',
|
||||
'customer.junior',
|
||||
'customer.junior.guardian',
|
||||
'customer.junior.guardian.customer',
|
||||
'customer.junior.guardian.customer.user',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { forwardRef, Inject, Injectable, UnprocessableEntityException } from '@nestjs/common';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import Decimal from 'decimal.js';
|
||||
import moment from 'moment';
|
||||
import { Transactional } from 'typeorm-transactional';
|
||||
@ -6,6 +7,8 @@ import {
|
||||
AccountTransactionWebhookRequest,
|
||||
CardTransactionWebhookRequest,
|
||||
} from '~/common/modules/neoleap/dtos/requests';
|
||||
import { NOTIFICATION_EVENTS } from '~/common/modules/notification/constants/event-names.constant';
|
||||
import { ITransactionCreatedEvent } from '~/common/modules/notification/interfaces/notification-events.interface';
|
||||
import { Transaction } from '../entities/transaction.entity';
|
||||
import { CustomerType, TransactionType } from '../enums';
|
||||
import { TransactionRepository } from '../repositories/transaction.repository';
|
||||
@ -27,6 +30,7 @@ export class TransactionService {
|
||||
private readonly transactionRepository: TransactionRepository,
|
||||
private readonly accountService: AccountService,
|
||||
@Inject(forwardRef(() => CardService)) private readonly cardService: CardService,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
) {}
|
||||
|
||||
@Transactional()
|
||||
@ -58,6 +62,15 @@ export class TransactionService {
|
||||
await this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber());
|
||||
}
|
||||
|
||||
const event: ITransactionCreatedEvent = {
|
||||
transaction,
|
||||
card,
|
||||
isTopUp: false,
|
||||
isChildSpending: card.customerType === CustomerType.CHILD,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
this.eventEmitter.emit(NOTIFICATION_EVENTS.TRANSACTION_CREATED, event);
|
||||
|
||||
return transaction;
|
||||
}
|
||||
|
||||
@ -74,12 +87,41 @@ export class TransactionService {
|
||||
const transaction = await this.transactionRepository.createAccountTransaction(account, body);
|
||||
await this.accountService.creditAccountBalance(account.accountReference, body.amount);
|
||||
|
||||
const accountWithCards = await this.accountService.getAccountByAccountNumber(body.accountId);
|
||||
const card = accountWithCards.cards?.[0]
|
||||
? await this.cardService.getCardById(accountWithCards.cards[0].id)
|
||||
: null;
|
||||
|
||||
if (card) {
|
||||
const event: ITransactionCreatedEvent = {
|
||||
transaction,
|
||||
card,
|
||||
isTopUp: true,
|
||||
isChildSpending: false,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
this.eventEmitter.emit(NOTIFICATION_EVENTS.TRANSACTION_CREATED, event);
|
||||
}
|
||||
|
||||
return transaction;
|
||||
}
|
||||
|
||||
async createInternalChildTransaction(cardId: string, amount: number) {
|
||||
const card = await this.cardService.getCardById(cardId);
|
||||
const transaction = await this.transactionRepository.createInternalChildTransaction(card, amount);
|
||||
|
||||
const event: ITransactionCreatedEvent = {
|
||||
transaction,
|
||||
card,
|
||||
isTopUp: true,
|
||||
isChildSpending: true,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
console.log(`[TransactionService] Emitting TRANSACTION_CREATED event for transaction ${transaction.id}`);
|
||||
this.eventEmitter.emit(NOTIFICATION_EVENTS.TRANSACTION_CREATED, event);
|
||||
console.log(`[TransactionService] Event emitted successfully`);
|
||||
|
||||
return transaction;
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Notification event names
|
||||
* These are the event identifiers used throughout the notification system
|
||||
*/
|
||||
export const NOTIFICATION_EVENTS = {
|
||||
// Transaction events
|
||||
TRANSACTION_CREATED: 'notification.transaction.created',
|
||||
|
||||
// Money Request events
|
||||
MONEY_REQUEST_CREATED: 'notification.money-request.created',
|
||||
MONEY_REQUEST_APPROVED: 'notification.money-request.approved',
|
||||
MONEY_REQUEST_DECLINED: 'notification.money-request.declined',
|
||||
} as const;
|
||||
|
||||
export type NotificationEventName =
|
||||
typeof NOTIFICATION_EVENTS[keyof typeof NOTIFICATION_EVENTS];
|
||||
|
||||
|
||||
|
||||
|
||||
3
src/common/modules/notification/constants/index.ts
Normal file
3
src/common/modules/notification/constants/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
// Export all constants from this folder
|
||||
export * from './event-names.constant';
|
||||
|
||||
@ -36,6 +36,9 @@ export class Notification {
|
||||
@Column('uuid', { name: 'user_id', nullable: true })
|
||||
userId!: string;
|
||||
|
||||
@Column('jsonb', { name: 'data', nullable: true })
|
||||
data?: Record<string, any>;
|
||||
|
||||
@ManyToOne(() => User, (user) => user.notifications, { onDelete: 'CASCADE', nullable: true })
|
||||
@JoinColumn({ name: 'user_id' })
|
||||
user!: User;
|
||||
|
||||
@ -1,7 +1,46 @@
|
||||
export enum NotificationScope {
|
||||
// Existing scopes
|
||||
USER_REGISTERED = 'USER_REGISTERED',
|
||||
TASK_COMPLETED = 'TASK_COMPLETED',
|
||||
GIFT_RECEIVED = 'GIFT_RECEIVED',
|
||||
OTP = 'OTP',
|
||||
USER_INVITED = 'USER_INVITED',
|
||||
|
||||
// Transaction notifications - Top-up
|
||||
CHILD_TOP_UP = 'CHILD_TOP_UP',
|
||||
PARENT_TOP_UP_CONFIRMATION = 'PARENT_TOP_UP_CONFIRMATION',
|
||||
|
||||
// Transaction notifications - Spending
|
||||
CHILD_SPENDING = 'CHILD_SPENDING',
|
||||
PARENT_SPENDING_ALERT = 'PARENT_SPENDING_ALERT',
|
||||
|
||||
// Money Request notifications
|
||||
MONEY_REQUEST_CREATED = 'MONEY_REQUEST_CREATED',
|
||||
MONEY_REQUEST_APPROVED = 'MONEY_REQUEST_APPROVED',
|
||||
MONEY_REQUEST_DECLINED = 'MONEY_REQUEST_DECLINED',
|
||||
}
|
||||
|
||||
/**
|
||||
* Critical notification scopes that require guaranteed delivery
|
||||
* These will use RabbitMQ/Kafka instead of Redis PubSub when configured
|
||||
*
|
||||
* Add scopes here when you need guaranteed delivery for specific notification types
|
||||
* Examples:
|
||||
* - ACCOUNT_LOCKED
|
||||
* - SUSPICIOUS_ACTIVITY
|
||||
* - LARGE_TRANSACTION_ALERT
|
||||
* - PAYMENT_FAILED
|
||||
*/
|
||||
export const CRITICAL_NOTIFICATION_SCOPES = new Set<NotificationScope>([
|
||||
// Add critical scopes here as needed
|
||||
// Example: NotificationScope.ACCOUNT_LOCKED,
|
||||
]);
|
||||
|
||||
/**
|
||||
* Check if a notification scope requires guaranteed delivery
|
||||
* @param scope - Notification scope to check
|
||||
* @returns true if the scope requires guaranteed delivery
|
||||
*/
|
||||
export function requiresGuaranteedDelivery(scope: NotificationScope): boolean {
|
||||
return CRITICAL_NOTIFICATION_SCOPES.has(scope);
|
||||
}
|
||||
@ -1 +1,3 @@
|
||||
export * from './notification-page-meta.interface';
|
||||
export * from './notification-events.interface';
|
||||
export * from './messaging-system.interface';
|
||||
@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Interface for messaging systems (Redis PubSub, RabbitMQ, Kafka, etc.)
|
||||
* Allows switching between different messaging systems based on notification requirements
|
||||
*/
|
||||
export interface IMessagingSystem {
|
||||
/**
|
||||
* Publish a notification event
|
||||
* @param channel - Channel/topic name
|
||||
* @param payload - Notification payload
|
||||
*/
|
||||
publish(channel: string, payload: any): Promise<void>;
|
||||
|
||||
/**
|
||||
* Subscribe to a channel
|
||||
* @param channel - Channel/topic name
|
||||
* @param handler - Message handler function
|
||||
*/
|
||||
subscribe(channel: string, handler: (message: any) => Promise<void>): Promise<void>;
|
||||
|
||||
/**
|
||||
* Get system name (for logging)
|
||||
*/
|
||||
getName(): string;
|
||||
}
|
||||
|
||||
@ -0,0 +1,63 @@
|
||||
import { Transaction } from '~/card/entities/transaction.entity';
|
||||
import { Card } from '~/card/entities/card.entity';
|
||||
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
|
||||
|
||||
/**
|
||||
* Event payload for when a transaction is created
|
||||
* Used to notify users about transactions (spending or top-ups)
|
||||
*/
|
||||
export interface ITransactionCreatedEvent {
|
||||
/** The transaction that was created */
|
||||
transaction: Transaction;
|
||||
|
||||
/** The card used in the transaction (with all relations loaded) */
|
||||
card: Card;
|
||||
|
||||
/** True if this is a top-up/load transaction, false if spending */
|
||||
isTopUp: boolean;
|
||||
|
||||
/** True if this transaction was made by a child (requires parent notification) */
|
||||
isChildSpending: boolean;
|
||||
|
||||
/** When the event occurred */
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event payload for when a money request is created
|
||||
* Used to notify parents when their child requests money
|
||||
*/
|
||||
export interface IMoneyRequestCreatedEvent {
|
||||
/** The money request that was created */
|
||||
moneyRequest: MoneyRequest;
|
||||
|
||||
/** When the event occurred */
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event payload for when a money request is approved
|
||||
* Used to notify children when their money request is approved
|
||||
*/
|
||||
export interface IMoneyRequestApprovedEvent {
|
||||
/** The money request that was approved */
|
||||
moneyRequest: MoneyRequest;
|
||||
|
||||
/** When the event occurred */
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event payload for when a money request is declined
|
||||
* Used to notify children when their money request is declined
|
||||
*/
|
||||
export interface IMoneyRequestDeclinedEvent {
|
||||
/** The money request that was declined */
|
||||
moneyRequest: MoneyRequest;
|
||||
|
||||
/** Rejection reason provided by parent */
|
||||
rejectionReason?: string;
|
||||
|
||||
/** When the event occurred */
|
||||
timestamp: Date;
|
||||
}
|
||||
@ -1 +1,3 @@
|
||||
export * from './notification-created.listener';
|
||||
export * from './transaction-notification.listener';
|
||||
export * from './money-request-notification.listener';
|
||||
|
||||
@ -0,0 +1,264 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
import { NotificationFactory, NotificationPreferences } from '../services/notification-factory.service';
|
||||
import { UserService } from '~/user/services/user.service';
|
||||
import { NOTIFICATION_EVENTS } from '../constants/event-names.constant';
|
||||
import {
|
||||
IMoneyRequestApprovedEvent,
|
||||
IMoneyRequestCreatedEvent,
|
||||
IMoneyRequestDeclinedEvent,
|
||||
} from '../interfaces/notification-events.interface';
|
||||
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||
import { User } from '~/user/entities';
|
||||
|
||||
/**
|
||||
* MoneyRequestNotificationListener
|
||||
*
|
||||
* Handles notifications for money request events.
|
||||
* Notifies parents when children request money, and children when requests are approved/declined.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Listen for money request events (created, approved, declined)
|
||||
* - Determine notification recipients (parent or child)
|
||||
* - Construct appropriate messages
|
||||
* - Fetch user preferences
|
||||
* - Call NotificationFactory to send
|
||||
*/
|
||||
@Injectable()
|
||||
export class MoneyRequestNotificationListener {
|
||||
private readonly logger = new Logger(MoneyRequestNotificationListener.name);
|
||||
|
||||
constructor(
|
||||
private readonly notificationFactory: NotificationFactory,
|
||||
private readonly userService: UserService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Handle money request created event
|
||||
* Notifies parent when child requests money
|
||||
*/
|
||||
@OnEvent(NOTIFICATION_EVENTS.MONEY_REQUEST_CREATED)
|
||||
async handleMoneyRequestCreated(event: IMoneyRequestCreatedEvent): Promise<void> {
|
||||
try {
|
||||
const { moneyRequest } = event;
|
||||
|
||||
this.logger.log(
|
||||
`Processing money request notification for request ${moneyRequest.id} - ` +
|
||||
`Amount: $${moneyRequest.amount}, Reason: ${moneyRequest.reason}`
|
||||
);
|
||||
|
||||
await this.notifyParentOfMoneyRequest(moneyRequest);
|
||||
|
||||
this.logger.log(
|
||||
`Money request notification processed successfully for request ${moneyRequest.id}`
|
||||
);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to process money request notification: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle money request approved event
|
||||
* Notifies child when their money request is approved
|
||||
*/
|
||||
@OnEvent(NOTIFICATION_EVENTS.MONEY_REQUEST_APPROVED)
|
||||
async handleMoneyRequestApproved(event: IMoneyRequestApprovedEvent): Promise<void> {
|
||||
try {
|
||||
const { moneyRequest } = event;
|
||||
|
||||
this.logger.log(
|
||||
`Processing money request approved notification for request ${moneyRequest.id}`
|
||||
);
|
||||
|
||||
await this.notifyChildOfApproval(moneyRequest);
|
||||
|
||||
this.logger.log(
|
||||
`Money request approved notification processed successfully for request ${moneyRequest.id}`
|
||||
);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to process money request approved notification: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle money request declined event
|
||||
* Notifies child when their money request is declined
|
||||
*/
|
||||
@OnEvent(NOTIFICATION_EVENTS.MONEY_REQUEST_DECLINED)
|
||||
async handleMoneyRequestDeclined(event: IMoneyRequestDeclinedEvent): Promise<void> {
|
||||
try {
|
||||
const { moneyRequest, rejectionReason } = event;
|
||||
|
||||
this.logger.log(
|
||||
`Processing money request declined notification for request ${moneyRequest.id}`
|
||||
);
|
||||
|
||||
await this.notifyChildOfRejection(moneyRequest, rejectionReason);
|
||||
|
||||
this.logger.log(
|
||||
`Money request declined notification processed successfully for request ${moneyRequest.id}`
|
||||
);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to process money request declined notification: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify parent when child requests money
|
||||
*/
|
||||
private async notifyParentOfMoneyRequest(moneyRequest: any): Promise<void> {
|
||||
try {
|
||||
const guardian = moneyRequest?.guardian;
|
||||
const parentUser = guardian?.customer?.user;
|
||||
|
||||
if (!parentUser) {
|
||||
this.logger.warn(`No parent user found for money request ${moneyRequest.id}, skipping notification`);
|
||||
return;
|
||||
}
|
||||
|
||||
const child = moneyRequest?.junior;
|
||||
const childUser = child?.customer?.user;
|
||||
const childName = childUser?.firstName || 'Your child';
|
||||
const amount = typeof moneyRequest.amount === 'string' ? parseFloat(moneyRequest.amount) : moneyRequest.amount;
|
||||
const reason = moneyRequest.reason || 'No reason provided';
|
||||
|
||||
this.logger.debug(
|
||||
`Notifying parent (user ${parentUser.id}): ${childName} requested $${amount} - ${reason}`
|
||||
);
|
||||
|
||||
await this.notificationFactory.send({
|
||||
userId: parentUser.id,
|
||||
title: 'Money Request',
|
||||
message: `${childName} requested $${amount.toFixed(2)}. Reason: ${reason}`,
|
||||
scope: NotificationScope.MONEY_REQUEST_CREATED,
|
||||
preferences: this.getUserPreferences(parentUser),
|
||||
data: {
|
||||
moneyRequestId: moneyRequest.id,
|
||||
childId: childUser?.id,
|
||||
childName: childName,
|
||||
amount: amount.toString(),
|
||||
reason: reason,
|
||||
timestamp: moneyRequest.createdAt.toISOString(),
|
||||
type: 'MONEY_REQUEST',
|
||||
action: 'VIEW_MONEY_REQUEST',
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`✅ Notified parent ${parentUser.id} about money request ${moneyRequest.id}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to notify parent of money request: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify child when their money request is approved
|
||||
*/
|
||||
private async notifyChildOfApproval(moneyRequest: any): Promise<void> {
|
||||
try {
|
||||
const child = moneyRequest?.junior;
|
||||
const childUser = child?.customer?.user;
|
||||
|
||||
if (!childUser) {
|
||||
this.logger.warn(`No child user found for money request ${moneyRequest.id}, skipping notification`);
|
||||
return;
|
||||
}
|
||||
|
||||
const amount = typeof moneyRequest.amount === 'string' ? parseFloat(moneyRequest.amount) : moneyRequest.amount;
|
||||
|
||||
this.logger.debug(
|
||||
`Notifying child (user ${childUser.id}): Money request of $${amount} was approved`
|
||||
);
|
||||
|
||||
await this.notificationFactory.send({
|
||||
userId: childUser.id,
|
||||
title: 'Money Request Approved',
|
||||
message: `Your request for $${amount.toFixed(2)} has been approved. The money has been added to your account.`,
|
||||
scope: NotificationScope.MONEY_REQUEST_APPROVED,
|
||||
preferences: this.getUserPreferences(childUser),
|
||||
data: {
|
||||
moneyRequestId: moneyRequest.id,
|
||||
amount: amount.toString(),
|
||||
timestamp: moneyRequest.updatedAt.toISOString(),
|
||||
type: 'MONEY_REQUEST_APPROVED',
|
||||
action: 'VIEW_MONEY_REQUEST',
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`✅ Notified child ${childUser.id} about approved money request ${moneyRequest.id}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to notify child of approval: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify child when their money request is declined
|
||||
*/
|
||||
private async notifyChildOfRejection(moneyRequest: any, rejectionReason?: string): Promise<void> {
|
||||
try {
|
||||
const child = moneyRequest?.junior;
|
||||
const childUser = child?.customer?.user;
|
||||
|
||||
if (!childUser) {
|
||||
this.logger.warn(`No child user found for money request ${moneyRequest.id}, skipping notification`);
|
||||
return;
|
||||
}
|
||||
|
||||
const amount = typeof moneyRequest.amount === 'string' ? parseFloat(moneyRequest.amount) : moneyRequest.amount;
|
||||
const reason = rejectionReason || 'No reason provided';
|
||||
|
||||
this.logger.debug(
|
||||
`Notifying child (user ${childUser.id}): Money request of $${amount} was declined`
|
||||
);
|
||||
|
||||
await this.notificationFactory.send({
|
||||
userId: childUser.id,
|
||||
title: 'Money Request Declined',
|
||||
message: `Your request for $${amount.toFixed(2)} has been declined. Reason: ${reason}`,
|
||||
scope: NotificationScope.MONEY_REQUEST_DECLINED,
|
||||
preferences: this.getUserPreferences(childUser),
|
||||
data: {
|
||||
moneyRequestId: moneyRequest.id,
|
||||
amount: amount.toString(),
|
||||
rejectionReason: reason,
|
||||
timestamp: moneyRequest.updatedAt.toISOString(),
|
||||
type: 'MONEY_REQUEST_DECLINED',
|
||||
action: 'VIEW_MONEY_REQUEST',
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`✅ Notified child ${childUser.id} about declined money request ${moneyRequest.id}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to notify child of rejection: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract user preferences from User entity
|
||||
* Converts User properties to NotificationPreferences interface
|
||||
*/
|
||||
private getUserPreferences(user: User): NotificationPreferences {
|
||||
return {
|
||||
isPushEnabled: user.isPushEnabled,
|
||||
isEmailEnabled: user.isEmailEnabled,
|
||||
isSmsEnabled: user.isSmsEnabled,
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -31,7 +31,7 @@ export class NotificationCreatedListener {
|
||||
return this.sendSMS(event.recipient!, event.message);
|
||||
|
||||
case NotificationChannel.PUSH:
|
||||
return this.sendPushNotification(event.userId, event.title, event.message);
|
||||
return this.sendPushNotification(event.userId, event.title, event.message, event.data);
|
||||
|
||||
case NotificationChannel.EMAIL:
|
||||
return this.sendEmail({
|
||||
@ -54,7 +54,12 @@ export class NotificationCreatedListener {
|
||||
}
|
||||
}
|
||||
|
||||
private async sendPushNotification(userId: string, title: string, body: string) {
|
||||
private async sendPushNotification(
|
||||
userId: string,
|
||||
title: string,
|
||||
body: string,
|
||||
data?: Record<string, any>,
|
||||
) {
|
||||
this.logger.log(`Sending push notification to user ${userId}`);
|
||||
const tokens = await this.deviceService.getTokens(userId);
|
||||
|
||||
@ -62,7 +67,19 @@ export class NotificationCreatedListener {
|
||||
this.logger.log(`No device tokens found for user ${userId}, but notification was created in the DB.`);
|
||||
return;
|
||||
}
|
||||
return this.firebaseService.sendNotification(tokens, title, body);
|
||||
|
||||
// Convert data to string values (Firebase requires string values in data payload)
|
||||
const stringData: Record<string, string> | undefined = data
|
||||
? Object.entries(data).reduce(
|
||||
(acc, [key, value]) => {
|
||||
acc[key] = String(value);
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
return this.firebaseService.sendNotification(tokens, title, body, stringData);
|
||||
}
|
||||
|
||||
private async sendSMS(to: string, body: string) {
|
||||
|
||||
@ -0,0 +1,353 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
import { I18nService } from 'nestjs-i18n';
|
||||
import { NotificationFactory, NotificationPreferences } from '../services/notification-factory.service';
|
||||
import { UserService } from '~/user/services/user.service';
|
||||
import { NOTIFICATION_EVENTS } from '../constants/event-names.constant';
|
||||
import { ITransactionCreatedEvent } from '../interfaces/notification-events.interface';
|
||||
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||
import { Transaction } from '~/card/entities/transaction.entity';
|
||||
import { Card } from '~/card/entities/card.entity';
|
||||
import { User } from '~/user/entities';
|
||||
import { UserLocale } from '~/core/enums/user-locale.enum';
|
||||
|
||||
/**
|
||||
* TransactionNotificationListener
|
||||
*
|
||||
* Handles notifications for transaction events.
|
||||
* Determines who should be notified and what message to send.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Listen for transaction events
|
||||
* - Determine notification recipients (child, parent, or both)
|
||||
* - Construct appropriate messages
|
||||
* - Fetch user preferences
|
||||
* - Call NotificationFactory to send
|
||||
*/
|
||||
@Injectable()
|
||||
export class TransactionNotificationListener {
|
||||
private readonly logger = new Logger(TransactionNotificationListener.name);
|
||||
|
||||
constructor(
|
||||
private readonly notificationFactory: NotificationFactory,
|
||||
private readonly userService: UserService,
|
||||
private readonly i18n: I18nService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Main event handler for transaction created events
|
||||
* Routes to appropriate notification logic based on transaction type
|
||||
*/
|
||||
@OnEvent(NOTIFICATION_EVENTS.TRANSACTION_CREATED)
|
||||
async handleTransactionCreated(event: ITransactionCreatedEvent): Promise<void> {
|
||||
try {
|
||||
console.log(`[TransactionNotificationListener] Event received: ${NOTIFICATION_EVENTS.TRANSACTION_CREATED}`);
|
||||
const { transaction, card, isTopUp, isChildSpending } = event;
|
||||
|
||||
this.logger.log(
|
||||
`Processing transaction notification for transaction ${transaction.id} - ` +
|
||||
`isTopUp: ${isTopUp}, isChildSpending: ${isChildSpending}`
|
||||
);
|
||||
|
||||
console.log(`[TransactionNotificationListener] Transaction: ${transaction.id}, Card: ${card?.id}, isTopUp: ${isTopUp}, isChildSpending: ${isChildSpending}`);
|
||||
|
||||
await this.notifyTransactionOwner(transaction, card, isTopUp, isChildSpending);
|
||||
|
||||
if (isChildSpending) {
|
||||
if (isTopUp) {
|
||||
await this.notifyParentOfTopUp(transaction, card);
|
||||
} else {
|
||||
await this.notifyParentOfChildSpending(transaction, card);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`Transaction notification processed successfully for transaction ${transaction.id}`
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error(`[TransactionNotificationListener] ERROR:`, error);
|
||||
this.logger.error(
|
||||
`Failed to process transaction notification: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the transaction owner (the cardholder)
|
||||
* Could be a child or a parent depending on whose card was used
|
||||
*/
|
||||
private async notifyTransactionOwner(
|
||||
transaction: Transaction,
|
||||
card: Card,
|
||||
isTopUp: boolean,
|
||||
isChildSpending: boolean
|
||||
): Promise<void> {
|
||||
try {
|
||||
const user = card?.customer?.user;
|
||||
if (!user) {
|
||||
this.logger.warn(`No user found for transaction ${transaction.id}, skipping notification`);
|
||||
return;
|
||||
}
|
||||
|
||||
const scope = isTopUp
|
||||
? NotificationScope.CHILD_TOP_UP
|
||||
: NotificationScope.CHILD_SPENDING;
|
||||
|
||||
const locale = this.getUserLocale(user);
|
||||
const amount = transaction.transactionAmount;
|
||||
const merchant = transaction.merchantName || 'merchant';
|
||||
const balance = card.account?.balance || 0;
|
||||
const currency = card.account?.currency || transaction.transactionCurrency || 'SAR';
|
||||
|
||||
let title: string;
|
||||
let message: string;
|
||||
|
||||
try {
|
||||
title = isTopUp
|
||||
? this.i18n.t('app.NOTIFICATION.CHILD_TOP_UP_TITLE', { lang: locale })
|
||||
: this.i18n.t('app.NOTIFICATION.CHILD_SPENDING_TITLE', { lang: locale });
|
||||
|
||||
message = isTopUp
|
||||
? this.i18n.t('app.NOTIFICATION.CHILD_TOP_UP_MESSAGE', {
|
||||
lang: locale,
|
||||
args: {
|
||||
amount: amount.toString(),
|
||||
currency: currency,
|
||||
balance: balance.toString(),
|
||||
},
|
||||
})
|
||||
: this.i18n.t('app.NOTIFICATION.CHILD_SPENDING_MESSAGE', {
|
||||
lang: locale,
|
||||
args: {
|
||||
amount: amount.toString(),
|
||||
currency: currency,
|
||||
merchant: merchant,
|
||||
balance: balance.toString(),
|
||||
},
|
||||
});
|
||||
} catch (i18nError: any) {
|
||||
console.error(`[TransactionNotificationListener] i18n error:`, i18nError);
|
||||
this.logger.error(`i18n translation failed: ${i18nError?.message}`, i18nError?.stack);
|
||||
// Fallback to English without i18n
|
||||
title = isTopUp ? 'Card Topped Up' : 'Purchase Successful';
|
||||
message = isTopUp
|
||||
? `You received ${amount} ${currency}. Total balance: ${balance} ${currency}`
|
||||
: `You spent ${amount} ${currency} at ${merchant}. Balance: ${balance} ${currency}`;
|
||||
}
|
||||
|
||||
this.logger.debug(
|
||||
`Notifying transaction owner (user ${user.id}) - Amount: ${amount} ${currency}, Merchant: ${merchant}`
|
||||
);
|
||||
|
||||
await this.notificationFactory.send({
|
||||
userId: user.id,
|
||||
title,
|
||||
message,
|
||||
scope,
|
||||
preferences: this.getUserPreferences(user),
|
||||
data: {
|
||||
transactionId: transaction.id,
|
||||
amount: amount.toString(),
|
||||
currency: currency,
|
||||
merchant: merchant,
|
||||
merchantCategory: transaction.merchantCategoryCode || 'OTHER',
|
||||
balance: balance.toString(),
|
||||
timestamp: transaction.transactionDate.toISOString(),
|
||||
type: isTopUp ? 'TOP_UP' : 'SPENDING',
|
||||
action: 'OPEN_TRANSACTION',
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`✅ Notified user ${user.id} for transaction ${transaction.id}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to notify transaction owner: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify parent when their child makes a purchase
|
||||
* This is a spending alert for parents to monitor their children's expenses
|
||||
*/
|
||||
private async notifyParentOfChildSpending(transaction: Transaction, card: Card): Promise<void> {
|
||||
try {
|
||||
this.logger.debug(`Checking for parent to notify about child spending`);
|
||||
|
||||
const customer = card?.customer;
|
||||
const parentUser = customer?.junior?.guardian?.customer?.user;
|
||||
|
||||
if (!parentUser) {
|
||||
this.logger.debug(`No parent found for transaction ${transaction.id}, skipping parent notification`);
|
||||
return;
|
||||
}
|
||||
|
||||
const childUser = customer.user;
|
||||
const locale = this.getUserLocale(parentUser);
|
||||
const defaultChildName = this.i18n.t('app.NOTIFICATION.YOUR_CHILD', { lang: locale });
|
||||
const childName = childUser?.firstName || defaultChildName;
|
||||
const amount = transaction.transactionAmount;
|
||||
const merchant = transaction.merchantName || 'a merchant';
|
||||
const balance = card.account?.balance || 0;
|
||||
const currency = card.account?.currency || transaction.transactionCurrency || 'SAR';
|
||||
|
||||
this.logger.debug(
|
||||
`Notifying parent (user ${parentUser.id}): ${childName} spent ${amount} ${currency} at ${merchant}`
|
||||
);
|
||||
|
||||
let title: string;
|
||||
let message: string;
|
||||
|
||||
try {
|
||||
title = this.i18n.t('app.NOTIFICATION.PARENT_SPENDING_TITLE', { lang: locale });
|
||||
message = this.i18n.t('app.NOTIFICATION.PARENT_SPENDING_MESSAGE', {
|
||||
lang: locale,
|
||||
args: {
|
||||
childName: childName,
|
||||
amount: amount.toString(),
|
||||
currency: currency,
|
||||
merchant: merchant,
|
||||
balance: balance.toString(),
|
||||
},
|
||||
});
|
||||
} catch (i18nError: any) {
|
||||
console.error(`[TransactionNotificationListener] i18n error in parent spending:`, i18nError);
|
||||
this.logger.error(`i18n translation failed: ${i18nError?.message}`, i18nError?.stack);
|
||||
title = 'Child Spending Alert';
|
||||
message = `${childName} spent ${amount} ${currency} at ${merchant}. Balance: ${balance} ${currency}`;
|
||||
}
|
||||
|
||||
await this.notificationFactory.send({
|
||||
userId: parentUser.id,
|
||||
title,
|
||||
message,
|
||||
scope: NotificationScope.PARENT_SPENDING_ALERT,
|
||||
preferences: this.getUserPreferences(parentUser),
|
||||
data: {
|
||||
transactionId: transaction.id,
|
||||
childId: childUser.id,
|
||||
childName: childName,
|
||||
amount: amount.toString(),
|
||||
currency: currency,
|
||||
merchant: merchant,
|
||||
merchantCategory: transaction.merchantCategoryCode || 'OTHER',
|
||||
balance: balance.toString(),
|
||||
timestamp: transaction.transactionDate.toISOString(),
|
||||
type: 'CHILD_SPENDING',
|
||||
action: 'OPEN_TRANSACTION',
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`✅ Notified parent ${parentUser.id} about child spending`);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to notify parent of child spending: ${ error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify parent when they top up their child's card
|
||||
* This is a confirmation notification for the parent
|
||||
*/
|
||||
private async notifyParentOfTopUp(transaction: Transaction, card: Card): Promise<void> {
|
||||
try {
|
||||
this.logger.debug(`Checking for parent to notify about top-up`);
|
||||
|
||||
const customer = card?.customer;
|
||||
const parentUser = customer?.junior?.guardian?.customer?.user;
|
||||
|
||||
if (!parentUser) {
|
||||
this.logger.debug(`No parent found for transaction ${transaction.id}, skipping parent notification`);
|
||||
return;
|
||||
}
|
||||
|
||||
const childUser = customer.user;
|
||||
const locale = this.getUserLocale(parentUser);
|
||||
const defaultChildName = this.i18n.t('app.NOTIFICATION.YOUR_CHILD', { lang: locale });
|
||||
const childName = childUser?.firstName || defaultChildName;
|
||||
const amount = transaction.transactionAmount;
|
||||
const balance = card.account?.balance || 0;
|
||||
const currency = card.account?.currency || transaction.transactionCurrency || 'SAR';
|
||||
|
||||
this.logger.debug(
|
||||
`Notifying parent (user ${parentUser.id}): Transferred ${amount} ${currency} to ${childName}`
|
||||
);
|
||||
|
||||
let title: string;
|
||||
let message: string;
|
||||
|
||||
try {
|
||||
title = this.i18n.t('app.NOTIFICATION.PARENT_TOP_UP_TITLE', { lang: locale });
|
||||
message = this.i18n.t('app.NOTIFICATION.PARENT_TOP_UP_MESSAGE', {
|
||||
lang: locale,
|
||||
args: {
|
||||
amount: amount.toString(),
|
||||
currency: currency,
|
||||
childName: childName,
|
||||
balance: balance.toString(),
|
||||
},
|
||||
});
|
||||
} catch (i18nError: any) {
|
||||
console.error(`[TransactionNotificationListener] i18n error in parent top-up:`, i18nError);
|
||||
this.logger.error(`i18n translation failed: ${i18nError?.message}`, i18nError?.stack);
|
||||
title = 'Top-Up Confirmation';
|
||||
message = `You transferred ${amount} ${currency} to ${childName}. Balance: ${balance} ${currency}`;
|
||||
}
|
||||
|
||||
await this.notificationFactory.send({
|
||||
userId: parentUser.id,
|
||||
title,
|
||||
message,
|
||||
scope: NotificationScope.PARENT_TOP_UP_CONFIRMATION,
|
||||
preferences: this.getUserPreferences(parentUser),
|
||||
data: {
|
||||
transactionId: transaction.id,
|
||||
childId: childUser.id,
|
||||
childName: childName,
|
||||
amount: amount.toString(),
|
||||
currency: currency,
|
||||
balance: balance.toString(),
|
||||
timestamp: transaction.transactionDate.toISOString(),
|
||||
type: 'TOP_UP',
|
||||
action: 'OPEN_TRANSACTION',
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`✅ Notified parent ${parentUser.id} about top-up`);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to notify parent of top-up: ${ error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract user preferences from User entity
|
||||
* Converts User properties to NotificationPreferences interface
|
||||
*/
|
||||
private getUserPreferences(user: User): NotificationPreferences {
|
||||
return {
|
||||
isPushEnabled: user.isPushEnabled,
|
||||
isEmailEnabled: user.isEmailEnabled,
|
||||
isSmsEnabled: user.isSmsEnabled,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user locale for i18n translations
|
||||
* Defaults to English if not specified
|
||||
* TODO: Add locale field to User entity in the future
|
||||
*/
|
||||
private getUserLocale(user: User): UserLocale {
|
||||
// For now, default to English
|
||||
// In the future, this can read from user.locale or user.preferences.locale
|
||||
return UserLocale.ENGLISH;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -8,9 +8,14 @@ import { buildMailerOptions, buildTwilioOptions } from '~/core/module-options';
|
||||
import { UserModule } from '~/user/user.module';
|
||||
import { NotificationsController } from './controllers';
|
||||
import { Notification } from './entities';
|
||||
import { NotificationCreatedListener } from './listeners';
|
||||
import {
|
||||
MoneyRequestNotificationListener,
|
||||
NotificationCreatedListener,
|
||||
TransactionNotificationListener,
|
||||
} from './listeners';
|
||||
import { NotificationsRepository } from './repositories';
|
||||
import { FirebaseService, NotificationsService, TwilioService } from './services';
|
||||
import { FirebaseService, NotificationFactory, NotificationsService, TwilioService } from './services';
|
||||
import { MessagingSystemFactory, RedisPubSubMessagingService } from './services/messaging';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@ -28,12 +33,17 @@ import { FirebaseService, NotificationsService, TwilioService } from './services
|
||||
],
|
||||
providers: [
|
||||
NotificationsService,
|
||||
NotificationFactory,
|
||||
FirebaseService,
|
||||
NotificationsRepository,
|
||||
TwilioService,
|
||||
NotificationCreatedListener,
|
||||
TransactionNotificationListener,
|
||||
MoneyRequestNotificationListener,
|
||||
RedisPubSubMessagingService,
|
||||
MessagingSystemFactory,
|
||||
],
|
||||
exports: [NotificationsService, NotificationCreatedListener],
|
||||
exports: [NotificationsService, NotificationFactory, NotificationCreatedListener],
|
||||
controllers: [NotificationsController],
|
||||
})
|
||||
export class NotificationModule {}
|
||||
|
||||
@ -1,29 +1,77 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as admin from 'firebase-admin';
|
||||
|
||||
@Injectable()
|
||||
export class FirebaseService {
|
||||
private readonly logger = new Logger(FirebaseService.name);
|
||||
|
||||
constructor(private readonly configService: ConfigService) {
|
||||
try {
|
||||
this.logger.log('🔥 Initializing Firebase Admin SDK...');
|
||||
|
||||
const projectId = this.configService.get('FIREBASE_PROJECT_ID');
|
||||
const clientEmail = this.configService.get('FIREBASE_CLIENT_EMAIL');
|
||||
const privateKey = this.configService.get('FIREBASE_PRIVATE_KEY');
|
||||
|
||||
// Log configuration (without exposing sensitive data)
|
||||
this.logger.log(`📋 Project ID: ${projectId}`);
|
||||
this.logger.log(`📋 Client Email: ${clientEmail}`);
|
||||
this.logger.log(`📋 Private Key: ${privateKey ? 'SET ✅' : 'MISSING ❌'}`);
|
||||
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert({
|
||||
projectId: this.configService.get('FIREBASE_PROJECT_ID'),
|
||||
clientEmail: this.configService.get('FIREBASE_CLIENT_EMAIL'),
|
||||
privateKey: this.configService.get('FIREBASE_PRIVATE_KEY').replace(/\\n/g, '\n'),
|
||||
projectId,
|
||||
clientEmail,
|
||||
privateKey: privateKey.replace(/\\n/g, '\n'),
|
||||
}),
|
||||
});
|
||||
|
||||
this.logger.log('✅ Firebase Admin SDK initialized successfully!');
|
||||
this.logger.log(`📱 Connected to project: ${projectId}`);
|
||||
} catch (error: any) {
|
||||
this.logger.error('❌ Failed to initialize Firebase Admin SDK');
|
||||
this.logger.error(`Error: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
sendNotification(tokens: string | string[], title: string, body: string) {
|
||||
this.logger.log(`Sending push notification to ${tokens}`);
|
||||
async sendNotification(tokens: string | string[], title: string, body: string, data?: Record<string, string>) {
|
||||
this.logger.log(
|
||||
`Sending push notification to ${Array.isArray(tokens) ? tokens.length : 1} device(s)`,
|
||||
);
|
||||
|
||||
try {
|
||||
const message = {
|
||||
notification: {
|
||||
title,
|
||||
body,
|
||||
},
|
||||
data: data || {},
|
||||
tokens: Array.isArray(tokens) ? tokens : [tokens],
|
||||
};
|
||||
|
||||
admin.messaging().sendEachForMulticast(message);
|
||||
const response = await admin.messaging().sendEachForMulticast(message);
|
||||
|
||||
this.logger.log(
|
||||
`✅ Push sent! Success: ${response.successCount}, Failed: ${response.failureCount}`,
|
||||
);
|
||||
|
||||
// Log failed tokens for debugging
|
||||
if (response.failureCount > 0) {
|
||||
response.responses.forEach((resp, idx) => {
|
||||
if (!resp.success) {
|
||||
this.logger.warn(
|
||||
`Failed to send to token ${idx}: ${resp.error?.code} - ${resp.error?.message}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error: any) {
|
||||
this.logger.error(`❌ Failed to send push notification: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
export * from './firebase.service';
|
||||
export * from './notification-factory.service';
|
||||
export * from './notifications.service';
|
||||
export * from './twilio.service';
|
||||
|
||||
@ -0,0 +1,3 @@
|
||||
export * from './redis-pubsub-messaging.service';
|
||||
export * from './messaging-system-factory.service';
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
import { Injectable, Logger, Optional } from '@nestjs/common';
|
||||
import { NotificationScope, requiresGuaranteedDelivery } from '../../enums/notification-scope.enum';
|
||||
import { IMessagingSystem } from '../../interfaces/messaging-system.interface';
|
||||
import { RedisPubSubMessagingService } from './redis-pubsub-messaging.service';
|
||||
|
||||
/**
|
||||
* Messaging System Factory
|
||||
*
|
||||
* Determines which messaging system to use based on notification requirements.
|
||||
*
|
||||
* - Regular notifications → Redis PubSub (fast, 2-5ms)
|
||||
* - Critical notifications → RabbitMQ/Kafka (guaranteed delivery, 20-50ms)
|
||||
*
|
||||
* Usage:
|
||||
* ```typescript
|
||||
* const system = factory.getMessagingSystem(NotificationScope.CHILD_SPENDING);
|
||||
* await system.publish('NOTIFICATION_CREATED', payload);
|
||||
* ```
|
||||
*/
|
||||
@Injectable()
|
||||
export class MessagingSystemFactory {
|
||||
private readonly logger = new Logger(MessagingSystemFactory.name);
|
||||
|
||||
constructor(
|
||||
private readonly redisPubSubService: RedisPubSubMessagingService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get the appropriate messaging system based on notification scope
|
||||
*
|
||||
* @param scope - Notification scope
|
||||
* @returns Messaging system to use
|
||||
*/
|
||||
getMessagingSystem(scope: NotificationScope): IMessagingSystem {
|
||||
const needsGuaranteedDelivery = requiresGuaranteedDelivery(scope);
|
||||
|
||||
if (needsGuaranteedDelivery) {
|
||||
this.logger.warn(
|
||||
`[Factory] Critical notification ${scope} requires guaranteed delivery, ` +
|
||||
`but RabbitMQ not configured. Falling back to Redis PubSub.`
|
||||
);
|
||||
return this.redisPubSubService;
|
||||
} else {
|
||||
this.logger.debug(`[Factory] Using Redis PubSub for notification: ${scope}`);
|
||||
return this.redisPubSubService;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default messaging system (Redis PubSub)
|
||||
*
|
||||
* @returns Default messaging system
|
||||
*/
|
||||
getDefaultMessagingSystem(): IMessagingSystem {
|
||||
return this.redisPubSubService;
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,55 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import { RedisClientType } from '@keyv/redis';
|
||||
import { IMessagingSystem } from '../../interfaces/messaging-system.interface';
|
||||
|
||||
/**
|
||||
* Redis PubSub Messaging System Implementation
|
||||
*
|
||||
* Fast, real-time messaging for regular notifications.
|
||||
* Uses Redis PubSub for 2-5ms latency.
|
||||
*
|
||||
* Note: Messages are not persisted (fire-and-forget).
|
||||
* Suitable for notifications that are already saved in PostgreSQL.
|
||||
*/
|
||||
@Injectable()
|
||||
export class RedisPubSubMessagingService implements IMessagingSystem {
|
||||
private readonly logger = new Logger(RedisPubSubMessagingService.name);
|
||||
|
||||
constructor(
|
||||
@Inject('REDIS_PUBLISHER') private readonly publisher: RedisClientType,
|
||||
@Inject('REDIS_SUBSCRIBER') private readonly subscriber: RedisClientType,
|
||||
) {}
|
||||
|
||||
getName(): string {
|
||||
return 'Redis PubSub';
|
||||
}
|
||||
|
||||
async publish(channel: string, payload: any): Promise<void> {
|
||||
try {
|
||||
const message = JSON.stringify(payload);
|
||||
const subscriberCount = await this.publisher.publish(channel, message);
|
||||
|
||||
this.logger.debug(
|
||||
`[Redis PubSub] Published to ${channel}, ${subscriberCount} subscriber(s) received`
|
||||
);
|
||||
} catch (error: any) {
|
||||
this.logger.error(`[Redis PubSub] Failed to publish to ${channel}: ${error?.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async subscribe(channel: string, handler: (message: any) => Promise<void>): Promise<void> {
|
||||
await this.subscriber.subscribe(channel, async (message) => {
|
||||
try {
|
||||
const data = JSON.parse(message);
|
||||
await handler(data);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`[Redis PubSub] Failed to process message from ${channel}: ${error?.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
this.logger.log(`[Redis PubSub] Subscribed to channel: ${channel}`);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,140 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { NotificationChannel } from '../enums/notification-channel.enum';
|
||||
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||
|
||||
/**
|
||||
* User notification preferences
|
||||
* Determines which channels are enabled for a user
|
||||
*/
|
||||
export interface NotificationPreferences {
|
||||
/** Whether push notifications are enabled */
|
||||
isPushEnabled: boolean;
|
||||
|
||||
/** Whether email notifications are enabled */
|
||||
isEmailEnabled: boolean;
|
||||
|
||||
/** Whether SMS notifications are enabled */
|
||||
isSmsEnabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload for sending a notification
|
||||
*/
|
||||
export interface NotificationPayload {
|
||||
/** ID of the user to notify */
|
||||
userId: string;
|
||||
|
||||
/** Notification title */
|
||||
title: string;
|
||||
|
||||
/** Notification message body */
|
||||
message: string;
|
||||
|
||||
/** Category/type of notification */
|
||||
scope: NotificationScope;
|
||||
|
||||
/**
|
||||
* User's notification preferences
|
||||
* If not provided, defaults to push-only
|
||||
*/
|
||||
preferences?: NotificationPreferences;
|
||||
|
||||
/** Additional data to attach to the notification */
|
||||
data?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* NotificationFactory
|
||||
*
|
||||
* Central service for sending notifications.
|
||||
* Independent service with no external dependencies (microservice-ready).
|
||||
*
|
||||
* Handles:
|
||||
* - Channel routing based on provided preferences
|
||||
* - Parallel notification delivery
|
||||
* - Error handling
|
||||
*
|
||||
* Note: Caller is responsible for providing user preferences.
|
||||
* This keeps the factory independent and testable.
|
||||
*
|
||||
* Usage:
|
||||
* await notificationFactory.send({
|
||||
* userId: 'user-123',
|
||||
* title: 'Transaction Alert',
|
||||
* message: 'You spent $50.00',
|
||||
* scope: NotificationScope.CHILD_SPENDING,
|
||||
* preferences: {
|
||||
* isPushEnabled: true,
|
||||
* isEmailEnabled: false,
|
||||
* isSmsEnabled: false,
|
||||
* },
|
||||
* });
|
||||
*/
|
||||
@Injectable()
|
||||
export class NotificationFactory {
|
||||
private readonly logger = new Logger(NotificationFactory.name);
|
||||
|
||||
constructor(
|
||||
private readonly notificationsService: NotificationsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Send a notification to a user
|
||||
* Routes to enabled channels based on provided preferences
|
||||
*
|
||||
* @param payload - Notification payload including preferences
|
||||
*/
|
||||
async send(payload: NotificationPayload): Promise<void> {
|
||||
try {
|
||||
this.logger.log(`Sending notification to user ${payload.userId} - ${payload.title}`);
|
||||
|
||||
const preferences = payload.preferences || {
|
||||
isPushEnabled: true,
|
||||
isEmailEnabled: false,
|
||||
isSmsEnabled: false,
|
||||
};
|
||||
|
||||
const promises: Promise<any>[] = [];
|
||||
|
||||
if (preferences.isPushEnabled) {
|
||||
this.logger.debug(`Routing to PUSH channel for user ${payload.userId}`);
|
||||
promises.push(
|
||||
this.sendToChannel(payload, NotificationChannel.PUSH)
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.all(promises);
|
||||
|
||||
this.logger.log(
|
||||
`Notification sent to user ${payload.userId} via ${promises.length} channel(s)`
|
||||
);
|
||||
} catch (error: any) {
|
||||
this.logger.error(
|
||||
`Failed to send notification to user ${payload.userId}: ${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
// Don't throw - prevents breaking the main business flow
|
||||
// Notification failures should not break transactions, etc.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send notification via a specific channel
|
||||
* Creates the notification record and publishes it for delivery
|
||||
*/
|
||||
private async sendToChannel(
|
||||
payload: NotificationPayload,
|
||||
channel: NotificationChannel
|
||||
): Promise<void> {
|
||||
await this.notificationsService.createNotification({
|
||||
userId: payload.userId,
|
||||
title: payload.title,
|
||||
message: payload.message,
|
||||
scope: payload.scope,
|
||||
channel,
|
||||
data: payload.data,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -8,6 +8,7 @@ import { SendEmailRequestDto } from '../dtos/request';
|
||||
import { Notification } from '../entities';
|
||||
import { EventType, NotificationChannel, NotificationScope } from '../enums';
|
||||
import { NotificationsRepository } from '../repositories';
|
||||
import { MessagingSystemFactory } from './messaging/messaging-system-factory.service';
|
||||
|
||||
@Injectable()
|
||||
export class NotificationsService {
|
||||
@ -17,6 +18,7 @@ export class NotificationsService {
|
||||
|
||||
@Inject(forwardRef(() => RedisPubSubService))
|
||||
private readonly redisPubSubService: RedisPubSubService,
|
||||
private readonly messagingSystemFactory: MessagingSystemFactory,
|
||||
) {}
|
||||
|
||||
async getNotifications(userId: string, pageOptionsDto: PageOptionsRequestDto) {
|
||||
@ -31,9 +33,29 @@ export class NotificationsService {
|
||||
return { notifications, count, unreadCount };
|
||||
}
|
||||
|
||||
createNotification(notification: Partial<Notification>) {
|
||||
async createNotification(notification: Partial<Notification>) {
|
||||
this.logger.log(`Creating notification for user ${notification.userId}`);
|
||||
return this.notificationRepository.createNotification(notification);
|
||||
const savedNotification = await this.notificationRepository.createNotification(notification);
|
||||
|
||||
const scope = notification.scope || NotificationScope.USER_REGISTERED;
|
||||
const messagingSystem = this.messagingSystemFactory.getMessagingSystem(scope);
|
||||
|
||||
this.logger.log(
|
||||
`Publishing ${EventType.NOTIFICATION_CREATED} event to ${messagingSystem.getName()}`
|
||||
);
|
||||
|
||||
messagingSystem.publish(EventType.NOTIFICATION_CREATED, {
|
||||
...savedNotification,
|
||||
data: notification.data || savedNotification.data,
|
||||
}).catch((error) => {
|
||||
this.logger.error(
|
||||
`Failed to publish notification ${savedNotification.id} to ${messagingSystem.getName()}: ` +
|
||||
`${error?.message || 'Unknown error'}`,
|
||||
error?.stack
|
||||
);
|
||||
});
|
||||
|
||||
return savedNotification;
|
||||
}
|
||||
|
||||
markAsRead(userId: string) {
|
||||
@ -42,34 +64,25 @@ export class NotificationsService {
|
||||
}
|
||||
|
||||
async sendEmailAsync(data: SendEmailRequestDto) {
|
||||
this.logger.log(`emitting ${EventType.NOTIFICATION_CREATED} event`);
|
||||
const notification = await this.createNotification({
|
||||
this.logger.log(`Creating email notification for ${data.to}`);
|
||||
await this.createNotification({
|
||||
recipient: data.to,
|
||||
title: data.subject,
|
||||
message: '',
|
||||
scope: NotificationScope.USER_INVITED,
|
||||
channel: NotificationChannel.EMAIL,
|
||||
});
|
||||
// return this.redisPubSubService.emit(EventType.NOTIFICATION_CREATED, notification, data.data);
|
||||
this.redisPubSubService.publishEvent(EventType.NOTIFICATION_CREATED, {
|
||||
...notification,
|
||||
data,
|
||||
data: data.data,
|
||||
});
|
||||
}
|
||||
|
||||
async sendOtpNotification(sendOtpRequest: ISendOtp, otp: string) {
|
||||
this.logger.log(`Sending OTP to ${sendOtpRequest.recipient}`);
|
||||
const notification = await this.createNotification({
|
||||
return this.createNotification({
|
||||
recipient: sendOtpRequest.recipient,
|
||||
title: OTP_TITLE,
|
||||
message: OTP_BODY.replace('{otp}', otp),
|
||||
scope: NotificationScope.OTP,
|
||||
channel: sendOtpRequest.otpType === OtpType.EMAIL ? NotificationChannel.EMAIL : NotificationChannel.SMS,
|
||||
});
|
||||
|
||||
this.logger.log(`emitting ${EventType.NOTIFICATION_CREATED} event`);
|
||||
return this.redisPubSubService.publishEvent(EventType.NOTIFICATION_CREATED, {
|
||||
...notification,
|
||||
data: { otp },
|
||||
});
|
||||
}
|
||||
|
||||
@ -32,7 +32,11 @@ export class RedisModule {
|
||||
},
|
||||
RedisPubSubService,
|
||||
],
|
||||
exports: [RedisPubSubService],
|
||||
exports: [
|
||||
RedisPubSubService,
|
||||
'REDIS_PUBLISHER',
|
||||
'REDIS_SUBSCRIBER',
|
||||
],
|
||||
imports: [NotificationModule],
|
||||
};
|
||||
}
|
||||
|
||||
@ -0,0 +1,16 @@
|
||||
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||
|
||||
export class AddDataColumnToNotifications1767172707881 implements MigrationInterface {
|
||||
name = 'AddDataColumnToNotifications1767172707881'
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE "notifications" ADD "data" jsonb`);
|
||||
await queryRunner.query(`ALTER TABLE "kyc_transactions" ALTER COLUMN "national_id" DROP DEFAULT`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE "kyc_transactions" ALTER COLUMN "national_id" SET DEFAULT ''`);
|
||||
await queryRunner.query(`ALTER TABLE "notifications" DROP COLUMN "data"`);
|
||||
}
|
||||
|
||||
}
|
||||
@ -6,6 +6,7 @@ export * from './1757433339849-add-reservation-amount-to-account-entity';
|
||||
export * from './1757915357218-add-deleted-at-column-to-junior';
|
||||
export * from './1760869651296-AddMerchantInfoToTransactions';
|
||||
export * from './1761032305682-AddUniqueConstraintToUserEmail';
|
||||
export * from './1767172707881-AddDataColumnToNotifications';
|
||||
export * from './1765804942393-AddKycFieldsAndTransactions';
|
||||
export * from './1765877128065-AddNationalIdToKycTransactions';
|
||||
export * from './1765891028260-RemoveOldCustomerColumns';
|
||||
|
||||
@ -110,5 +110,16 @@
|
||||
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
|
||||
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر.",
|
||||
"NOT_FOUND": "لم يتم العثور على البطاقة."
|
||||
},
|
||||
"NOTIFICATION": {
|
||||
"CHILD_TOP_UP_TITLE": "تم شحن البطاقة",
|
||||
"CHILD_TOP_UP_MESSAGE": "لقد استلمت {amount} {currency}. الرصيد الإجمالي: {balance} {currency}",
|
||||
"CHILD_SPENDING_TITLE": "تمت العملية بنجاح",
|
||||
"CHILD_SPENDING_MESSAGE": "لقد أنفقت {amount} {currency} في {merchant}. الرصيد: {balance} {currency}",
|
||||
"PARENT_TOP_UP_TITLE": "تأكيد الشحن",
|
||||
"PARENT_TOP_UP_MESSAGE": "لقد قمت بتحويل {amount} {currency} إلى {childName}. الرصيد: {balance} {currency}",
|
||||
"PARENT_SPENDING_TITLE": "تنبيه إنفاق الطفل",
|
||||
"PARENT_SPENDING_MESSAGE": "أنفق {childName} {amount} {currency} في {merchant}. الرصيد: {balance} {currency}",
|
||||
"YOUR_CHILD": "طفلك"
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,5 +109,16 @@
|
||||
"INSUFFICIENT_BALANCE": "The card does not have sufficient balance to complete this transfer.",
|
||||
"DOES_NOT_BELONG_TO_GUARDIAN": "The card does not belong to the guardian.",
|
||||
"NOT_FOUND": "The card was not found."
|
||||
},
|
||||
"NOTIFICATION": {
|
||||
"CHILD_TOP_UP_TITLE": "Card Topped Up",
|
||||
"CHILD_TOP_UP_MESSAGE": "You received {amount} {currency}. Total balance: {balance} {currency}",
|
||||
"CHILD_SPENDING_TITLE": "Purchase Successful",
|
||||
"CHILD_SPENDING_MESSAGE": "You spent {amount} {currency} at {merchant}. Balance: {balance} {currency}",
|
||||
"PARENT_TOP_UP_TITLE": "Top-Up Confirmation",
|
||||
"PARENT_TOP_UP_MESSAGE": "You transferred {amount} {currency} to {childName}. Balance: {balance} {currency}",
|
||||
"PARENT_SPENDING_TITLE": "Child Spending Alert",
|
||||
"PARENT_SPENDING_MESSAGE": "{childName} spent {amount} {currency} at {merchant}. Balance: {balance} {currency}",
|
||||
"YOUR_CHILD": "Your child"
|
||||
}
|
||||
}
|
||||
|
||||
@ -56,7 +56,33 @@ export class MoneyRequestsRepository {
|
||||
}
|
||||
return this.moneyRequestRepository.findOne({
|
||||
where: whereCondition,
|
||||
relations: ['junior', 'junior.customer', 'junior.customer.user', 'junior.customer.user.profilePicture'],
|
||||
relations: [
|
||||
'junior',
|
||||
'junior.customer',
|
||||
'junior.customer.user',
|
||||
'junior.customer.user.profilePicture',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
findByIdWithAllRelations(id: string, userId?: string, role?: Roles): Promise<MoneyRequest | null> {
|
||||
const whereCondition: any = { id };
|
||||
if (role === Roles.JUNIOR) {
|
||||
whereCondition.juniorId = userId;
|
||||
} else {
|
||||
whereCondition.guardianId = userId;
|
||||
}
|
||||
return this.moneyRequestRepository.findOne({
|
||||
where: whereCondition,
|
||||
relations: [
|
||||
'junior',
|
||||
'junior.customer',
|
||||
'junior.customer.user',
|
||||
'junior.customer.user.profilePicture',
|
||||
'guardian',
|
||||
'guardian.customer',
|
||||
'guardian.customer.user',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,13 @@
|
||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { Transactional } from 'typeorm-transactional';
|
||||
import { Roles } from '~/auth/enums';
|
||||
import { NOTIFICATION_EVENTS } from '~/common/modules/notification/constants/event-names.constant';
|
||||
import {
|
||||
IMoneyRequestApprovedEvent,
|
||||
IMoneyRequestCreatedEvent,
|
||||
IMoneyRequestDeclinedEvent,
|
||||
} from '~/common/modules/notification/interfaces/notification-events.interface';
|
||||
import { OciService } from '~/document/services';
|
||||
import { Junior } from '~/junior/entities/junior.entity';
|
||||
import { JuniorService } from '~/junior/services';
|
||||
@ -16,10 +23,19 @@ export class MoneyRequestsService {
|
||||
private readonly moneyRequestsRepository: MoneyRequestsRepository,
|
||||
private readonly juniorService: JuniorService,
|
||||
private readonly ociService: OciService,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
) {}
|
||||
async createMoneyRequest(juniorId: string, body: CreateMoneyRequestDto) {
|
||||
const junior = await this.juniorService.findJuniorById(juniorId);
|
||||
const moneyRequest = await this.moneyRequestsRepository.createMoneyRequest(junior.id, junior.guardianId, body);
|
||||
const moneyRequestWithRelations = await this.moneyRequestsRepository.findByIdWithAllRelations(moneyRequest.id);
|
||||
|
||||
const event: IMoneyRequestCreatedEvent = {
|
||||
moneyRequest: moneyRequestWithRelations!,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
this.eventEmitter.emit(NOTIFICATION_EVENTS.MONEY_REQUEST_CREATED, event);
|
||||
|
||||
return this.findById(moneyRequest.id);
|
||||
}
|
||||
|
||||
@ -63,6 +79,13 @@ export class MoneyRequestsService {
|
||||
moneyRequest.guardianId,
|
||||
),
|
||||
]);
|
||||
|
||||
const updatedMoneyRequest = await this.moneyRequestsRepository.findByIdWithAllRelations(id, guardianId, Roles.GUARDIAN);
|
||||
const event: IMoneyRequestApprovedEvent = {
|
||||
moneyRequest: updatedMoneyRequest!,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
this.eventEmitter.emit(NOTIFICATION_EVENTS.MONEY_REQUEST_APPROVED, event);
|
||||
}
|
||||
|
||||
async rejectMoneyRequest(
|
||||
@ -85,6 +108,14 @@ export class MoneyRequestsService {
|
||||
}
|
||||
|
||||
await this.moneyRequestsRepository.rejectMoneyRequest(id, rejectionReasondto?.rejectionReason);
|
||||
|
||||
const updatedMoneyRequest = await this.moneyRequestsRepository.findByIdWithAllRelations(id, guardianId, Roles.GUARDIAN);
|
||||
const event: IMoneyRequestDeclinedEvent = {
|
||||
moneyRequest: updatedMoneyRequest!,
|
||||
rejectionReason: rejectionReasondto?.rejectionReason,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
this.eventEmitter.emit(NOTIFICATION_EVENTS.MONEY_REQUEST_DECLINED, event);
|
||||
}
|
||||
|
||||
private async prepareJuniorImages(juniors: Junior[]) {
|
||||
|
||||
@ -11,6 +11,10 @@ export class DeviceRepository {
|
||||
return this.deviceRepository.findOne({ where: { deviceId, userId } });
|
||||
}
|
||||
|
||||
findByDeviceId(deviceId: string) {
|
||||
return this.deviceRepository.findOne({ where: { deviceId } });
|
||||
}
|
||||
|
||||
createDevice(data: Partial<Device>) {
|
||||
return this.deviceRepository.save(data);
|
||||
}
|
||||
|
||||
@ -10,6 +10,11 @@ export class DeviceService {
|
||||
return this.deviceRepository.findUserDeviceById(deviceId, userId);
|
||||
}
|
||||
|
||||
findByDeviceId(deviceId: string) {
|
||||
this.logger.log(`Finding device with id ${deviceId} (any user)`);
|
||||
return this.deviceRepository.findByDeviceId(deviceId);
|
||||
}
|
||||
|
||||
createDevice(data: Partial<Device>) {
|
||||
this.logger.log(`Creating device with data ${JSON.stringify(data)}`);
|
||||
return this.deviceRepository.createDevice(data);
|
||||
|
||||
Reference in New Issue
Block a user