mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2026-03-10 18:41:46 +00:00
Compare commits
51 Commits
fix/verfy-
...
f5c3b03264
| Author | SHA1 | Date | |
|---|---|---|---|
| f5c3b03264 | |||
| a09b84e475 | |||
| 4305c4b75f | |||
| 7c9e0f0b51 | |||
| 1086166e04 | |||
| 6d6dc1471f | |||
| 1b0d6cb284 | |||
| c963b57904 | |||
| 145e6c62b8 | |||
| 45acf73a4a | |||
| d3ff755439 | |||
| 21653efc46 | |||
| 63b0a42eca | |||
| b1cda5e7dc | |||
| 2c8de913f8 | |||
| 170aa903c7 | |||
| 2f74aa36a9 | |||
| 2562515574 | |||
| 93b509b256 | |||
| 9c93a35093 | |||
| d77d59a793 | |||
| 110a6fb0ee | |||
| 83787c7c67 | |||
| 24bcb10d76 | |||
| a3cdf50cb7 | |||
| cfd02e8c30 | |||
| 0fb76d712d | |||
| 5e708c16fe | |||
| fe11f35b32 | |||
| 3200f60821 | |||
| 24521c4223 | |||
| e8127970f6 | |||
| 07d4a83cf9 | |||
| ce1f6341b7 | |||
| 2a62787c3b | |||
| 91dea22f45 | |||
| ef28c75f9b | |||
| c007ac584f | |||
| d2d83549b2 | |||
| 506974afc8 | |||
| 95f8cfbfdf | |||
| 8b00cda23d | |||
| 12cc88a50e | |||
| 2172051093 | |||
| a6a573957c | |||
| d6fb5f48d9 | |||
| b0011eb7cc | |||
| 99af65a300 | |||
| 0c9b40132a | |||
| 3b295ea79f | |||
| 5ffe18ede3 |
0
queries/Query.sql
Normal file
0
queries/Query.sql
Normal file
@ -1,5 +1,5 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
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';
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
export class JuniorLoginRequestDto {
|
export class JuniorLoginRequestDto {
|
||||||
@ApiProperty({ example: 'test@junior.com' })
|
@ApiProperty({ example: 'test@junior.com' })
|
||||||
@ -9,4 +9,27 @@ export class JuniorLoginRequestDto {
|
|||||||
@ApiProperty({ example: 'Abcd1234@' })
|
@ApiProperty({ example: 'Abcd1234@' })
|
||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
||||||
password!: string;
|
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;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'Asia/Riyadh',
|
||||||
|
description: 'Device timezone (auto-detected from device OS)',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.timezone' }) })
|
||||||
|
timezone?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -21,4 +21,27 @@ export class LoginRequestDto {
|
|||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.password' }) })
|
||||||
@ValidateIf((o) => o.grantType === GrantType.PASSWORD)
|
@ValidateIf((o) => o.grantType === GrantType.PASSWORD)
|
||||||
password!: string;
|
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;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'Asia/Riyadh',
|
||||||
|
description: 'Device timezone (auto-detected from device OS)',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.timezone' }) })
|
||||||
|
timezone?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,5 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import {
|
import {
|
||||||
IsDateString,
|
|
||||||
IsEmail,
|
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsNumberString,
|
IsNumberString,
|
||||||
@ -15,7 +13,7 @@ import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
|||||||
import { COUNTRY_CODE_REGEX, PASSWORD_REGEX } from '~/auth/constants';
|
import { COUNTRY_CODE_REGEX, PASSWORD_REGEX } from '~/auth/constants';
|
||||||
import { CountryIso } from '~/common/enums';
|
import { CountryIso } from '~/common/enums';
|
||||||
import { DEFAULT_OTP_LENGTH } from '~/common/modules/otp/constants';
|
import { DEFAULT_OTP_LENGTH } from '~/common/modules/otp/constants';
|
||||||
import { IsAbove18, IsValidPhoneNumber } from '~/core/decorators/validations';
|
import { IsValidPhoneNumber } from '~/core/decorators/validations';
|
||||||
|
|
||||||
export class VerifyUserRequestDto {
|
export class VerifyUserRequestDto {
|
||||||
@ApiProperty({ example: '+962' })
|
@ApiProperty({ example: '+962' })
|
||||||
@ -39,11 +37,6 @@ export class VerifyUserRequestDto {
|
|||||||
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.lastName' }) })
|
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.lastName' }) })
|
||||||
lastName!: string;
|
lastName!: string;
|
||||||
|
|
||||||
@ApiProperty({ example: '2001-01-01' })
|
|
||||||
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.dateOfBirth' }) })
|
|
||||||
@IsAbove18({ message: i18n('validation.IsAbove18', { path: 'general', property: 'customer.dateOfBirth' }) })
|
|
||||||
dateOfBirth!: Date;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'JO' })
|
@ApiProperty({ example: 'JO' })
|
||||||
@IsEnum(CountryIso, {
|
@IsEnum(CountryIso, {
|
||||||
message: i18n('validation.IsEnum', { path: 'general', property: 'customer.countryOfResidence' }),
|
message: i18n('validation.IsEnum', { path: 'general', property: 'customer.countryOfResidence' }),
|
||||||
@ -51,10 +44,38 @@ export class VerifyUserRequestDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
countryOfResidence: CountryIso = CountryIso.SAUDI_ARABIA;
|
countryOfResidence: CountryIso = CountryIso.SAUDI_ARABIA;
|
||||||
|
|
||||||
@ApiProperty({ example: 'test@test.com' })
|
// Address fields (optional during registration, required for card creation)
|
||||||
@IsEmail({}, { message: i18n('validation.IsEmail', { path: 'general', property: 'auth.email' }) })
|
@ApiProperty({ example: 'SA', description: 'Country code', required: false })
|
||||||
|
@IsEnum(CountryIso, {
|
||||||
|
message: i18n('validation.IsEnum', { path: 'general', property: 'customer.country' }),
|
||||||
|
})
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
email!: string;
|
country?: CountryIso;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Riyadh', description: 'Region/Province', required: false })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.region' }) })
|
||||||
|
@IsOptional()
|
||||||
|
region?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Riyadh', description: 'City', required: false })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.city' }) })
|
||||||
|
@IsOptional()
|
||||||
|
city?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Al Olaya', description: 'Neighborhood/District', required: false })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.neighborhood' }) })
|
||||||
|
@IsOptional()
|
||||||
|
neighborhood?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'King Fahd Road', description: 'Street name', required: false })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.street' }) })
|
||||||
|
@IsOptional()
|
||||||
|
street?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '123', description: 'Building number', required: false })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.building' }) })
|
||||||
|
@IsOptional()
|
||||||
|
building?: string;
|
||||||
|
|
||||||
@ApiProperty({ example: 'Abcd1234@' })
|
@ApiProperty({ example: 'Abcd1234@' })
|
||||||
@Matches(PASSWORD_REGEX, {
|
@Matches(PASSWORD_REGEX, {
|
||||||
@ -80,4 +101,27 @@ export class VerifyUserRequestDto {
|
|||||||
message: i18n('validation.MinLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
|
message: i18n('validation.MinLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
|
||||||
})
|
})
|
||||||
otp!: string;
|
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;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'Asia/Riyadh',
|
||||||
|
description: 'Device timezone (auto-detected from device OS)',
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.timezone' }) })
|
||||||
|
timezone?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -41,14 +41,6 @@ export class AuthService {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
async sendRegisterOtp(body: CreateUnverifiedUserRequestDto) {
|
async sendRegisterOtp(body: CreateUnverifiedUserRequestDto) {
|
||||||
if (body.email) {
|
|
||||||
const isEmailUsed = await this.userService.findUser({ email: body.email, isEmailVerified: true });
|
|
||||||
if (isEmailUsed) {
|
|
||||||
this.logger.error(`Email ${body.email} is already used`);
|
|
||||||
throw new BadRequestException('USER.EMAIL_ALREADY_TAKEN');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (body.password !== body.confirmPassword) {
|
if (body.password !== body.confirmPassword) {
|
||||||
this.logger.error('Password and confirm password do not match');
|
this.logger.error('Password and confirm password do not match');
|
||||||
throw new BadRequestException('AUTH.PASSWORD_MISMATCH');
|
throw new BadRequestException('AUTH.PASSWORD_MISMATCH');
|
||||||
@ -94,6 +86,12 @@ export class AuthService {
|
|||||||
|
|
||||||
const tokens = await this.generateAuthToken(user);
|
const tokens = await this.generateAuthToken(user);
|
||||||
this.logger.log(`User with phone number ${user.fullPhoneNumber} verified successfully`);
|
this.logger.log(`User with phone number ${user.fullPhoneNumber} verified successfully`);
|
||||||
|
|
||||||
|
// Register/update device with FCM token and timezone if provided
|
||||||
|
if (verifyUserDto.fcmToken && verifyUserDto.deviceId) {
|
||||||
|
await this.registerDeviceToken(user.id, verifyUserDto.deviceId, verifyUserDto.fcmToken, verifyUserDto.timezone);
|
||||||
|
}
|
||||||
|
|
||||||
return [tokens, user];
|
return [tokens, user];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -279,6 +277,12 @@ export class AuthService {
|
|||||||
|
|
||||||
const tokens = await this.generateAuthToken(user);
|
const tokens = await this.generateAuthToken(user);
|
||||||
this.logger.log(`Password validated successfully for user`);
|
this.logger.log(`Password validated successfully for user`);
|
||||||
|
|
||||||
|
// Register/update device with FCM token and timezone if provided
|
||||||
|
if (loginDto.fcmToken && loginDto.deviceId) {
|
||||||
|
await this.registerDeviceToken(user.id, loginDto.deviceId, loginDto.fcmToken, loginDto.timezone);
|
||||||
|
}
|
||||||
|
|
||||||
return [tokens, user];
|
return [tokens, user];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -299,9 +303,76 @@ export class AuthService {
|
|||||||
|
|
||||||
const tokens = await this.generateAuthToken(user);
|
const tokens = await this.generateAuthToken(user);
|
||||||
this.logger.log(`Password validated successfully for user`);
|
this.logger.log(`Password validated successfully for user`);
|
||||||
|
|
||||||
|
// Register/update device with FCM token and timezone if provided
|
||||||
|
if (juniorLoginDto.fcmToken && juniorLoginDto.deviceId) {
|
||||||
|
await this.registerDeviceToken(user.id, juniorLoginDto.deviceId, juniorLoginDto.fcmToken, juniorLoginDto.timezone);
|
||||||
|
}
|
||||||
|
|
||||||
return [tokens, user];
|
return [tokens, user];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register or update device with FCM token and timezone
|
||||||
|
* This method handles:
|
||||||
|
* 1. Device already exists for this user → Update FCM token and timezone
|
||||||
|
* 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, timezone?: 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, timezone, and last access time
|
||||||
|
await this.deviceService.updateDevice(deviceId, {
|
||||||
|
fcmToken,
|
||||||
|
userId,
|
||||||
|
timezone, // Update timezone if provided
|
||||||
|
lastAccessOn: new Date(),
|
||||||
|
});
|
||||||
|
this.logger.log(`Device ${deviceId} updated with new FCM token and timezone 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,
|
||||||
|
timezone, // Update timezone if provided
|
||||||
|
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,
|
||||||
|
timezone, // Store timezone if provided
|
||||||
|
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) {
|
private async generateAuthToken(user: User) {
|
||||||
this.logger.log(`Generating auth token for user with id ${user.id}`);
|
this.logger.log(`Generating auth token for user with id ${user.id}`);
|
||||||
const [accessToken, refreshToken] = await Promise.all([
|
const [accessToken, refreshToken] = await Promise.all([
|
||||||
|
|||||||
@ -27,7 +27,7 @@ import { TransactionService } from './services/transaction.service';
|
|||||||
AccountService,
|
AccountService,
|
||||||
AccountRepository,
|
AccountRepository,
|
||||||
],
|
],
|
||||||
exports: [CardService, TransactionService],
|
exports: [CardService, TransactionService, AccountService],
|
||||||
controllers: [CardsController],
|
controllers: [CardsController],
|
||||||
})
|
})
|
||||||
export class CardModule {}
|
export class CardModule {}
|
||||||
|
|||||||
@ -42,7 +42,18 @@ export class CardRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getCardById(id: string): Promise<Card | null> {
|
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> {
|
findCardByChildId(guardianId: string, childId: string): Promise<Card | null> {
|
||||||
@ -59,14 +70,30 @@ export class CardRepository {
|
|||||||
getCardByVpan(vpan: string): Promise<Card | null> {
|
getCardByVpan(vpan: string): Promise<Card | null> {
|
||||||
return this.cardRepository.findOne({
|
return this.cardRepository.findOne({
|
||||||
where: { vpan },
|
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> {
|
getCardByCustomerId(customerId: string): Promise<Card | null> {
|
||||||
return this.cardRepository.findOne({
|
return this.cardRepository.findOne({
|
||||||
where: { customerId },
|
where: { customerId },
|
||||||
relations: ['account'],
|
relations: [
|
||||||
|
'account',
|
||||||
|
'customer',
|
||||||
|
'customer.user',
|
||||||
|
'customer.junior',
|
||||||
|
'customer.junior.guardian',
|
||||||
|
'customer.junior.guardian.customer',
|
||||||
|
'customer.junior.guardian.customer.user',
|
||||||
|
],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -64,9 +64,8 @@ export class AccountService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
increaseReservedBalance(account: Account, amount: number) {
|
increaseReservedBalance(account: Account, amount: number) {
|
||||||
if (account.balance < account.reservedBalance + amount) {
|
// Balance check is performed by the caller (e.g., transferToChild)
|
||||||
throw new UnprocessableEntityException('CARD.INSUFFICIENT_BALANCE');
|
// to ensure correct account (guardian vs child) is validated
|
||||||
}
|
|
||||||
return this.accountRepository.increaseReservedBalance(account.id, amount);
|
return this.accountRepository.increaseReservedBalance(account.id, amount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,9 @@
|
|||||||
import { BadRequestException, forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
|
import { BadRequestException, forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||||
import Decimal from 'decimal.js';
|
import Decimal from 'decimal.js';
|
||||||
import { Transactional } from 'typeorm-transactional';
|
import { Transactional } from 'typeorm-transactional';
|
||||||
|
import { NOTIFICATION_EVENTS } from '~/common/modules/notification/constants/event-names.constant';
|
||||||
|
import { ICardBlockedEvent, ICardCreatedEvent } from '~/common/modules/notification/interfaces/notification-events.interface';
|
||||||
import { AccountCardStatusChangedWebhookRequest } from '~/common/modules/neoleap/dtos/requests';
|
import { AccountCardStatusChangedWebhookRequest } from '~/common/modules/neoleap/dtos/requests';
|
||||||
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
||||||
import { Customer } from '~/customer/entities';
|
import { Customer } from '~/customer/entities';
|
||||||
@ -8,7 +11,7 @@ import { KycStatus } from '~/customer/enums';
|
|||||||
import { CustomerService } from '~/customer/services';
|
import { CustomerService } from '~/customer/services';
|
||||||
import { OciService } from '~/document/services';
|
import { OciService } from '~/document/services';
|
||||||
import { Card } from '../entities';
|
import { Card } from '../entities';
|
||||||
import { CardColors } from '../enums';
|
import { CardColors, CardStatus } from '../enums';
|
||||||
import { CardStatusMapper } from '../mappers/card-status.mapper';
|
import { CardStatusMapper } from '../mappers/card-status.mapper';
|
||||||
import { CardRepository } from '../repositories';
|
import { CardRepository } from '../repositories';
|
||||||
import { AccountService } from './account.service';
|
import { AccountService } from './account.service';
|
||||||
@ -24,6 +27,7 @@ export class CardService {
|
|||||||
@Inject(forwardRef(() => TransactionService)) private readonly transactionService: TransactionService,
|
@Inject(forwardRef(() => TransactionService)) private readonly transactionService: TransactionService,
|
||||||
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
||||||
@Inject(forwardRef(() => CustomerService)) private readonly customerService: CustomerService,
|
@Inject(forwardRef(() => CustomerService)) private readonly customerService: CustomerService,
|
||||||
|
private readonly eventEmitter: EventEmitter2,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
@ -34,15 +38,40 @@ export class CardService {
|
|||||||
throw new BadRequestException('CUSTOMER.KYC_NOT_APPROVED');
|
throw new BadRequestException('CUSTOMER.KYC_NOT_APPROVED');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!customer.neoleapExternalCustomerId) {
|
||||||
|
throw new BadRequestException('CUSTOMER.KYC_NOT_COMPLETED');
|
||||||
|
}
|
||||||
|
|
||||||
if (customer.cards.length > 0) {
|
if (customer.cards.length > 0) {
|
||||||
throw new BadRequestException('CUSTOMER.ALREADY_HAS_CARD');
|
throw new BadRequestException('CUSTOMER.ALREADY_HAS_CARD');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate required fields for card creation
|
||||||
|
const missingFields = [];
|
||||||
|
if (!customer.nationalId) missingFields.push('nationalId');
|
||||||
|
if (!customer.dateOfBirth) missingFields.push('dateOfBirth');
|
||||||
|
if (!customer.nationalIdExpiry) missingFields.push('nationalIdExpiry');
|
||||||
|
|
||||||
|
if (missingFields.length > 0) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`CUSTOMER.MISSING_REQUIRED_FIELDS: ${missingFields.join(', ')}. Please complete your profile.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const data = await this.neoleapService.createApplication(customer);
|
const data = await this.neoleapService.createApplication(customer);
|
||||||
const account = await this.accountService.createAccount(data);
|
const account = await this.accountService.createAccount(data);
|
||||||
const createdCard = await this.cardRepository.createCard(customerId, account.id, data);
|
const createdCard = await this.cardRepository.createCard(customerId, account.id, data);
|
||||||
|
|
||||||
return this.getCardById(createdCard.id);
|
const cardWithRelations = await this.getCardById(createdCard.id);
|
||||||
|
|
||||||
|
const event: ICardCreatedEvent = {
|
||||||
|
card: cardWithRelations,
|
||||||
|
timestamp: new Date(),
|
||||||
|
};
|
||||||
|
this.eventEmitter.emit(NOTIFICATION_EVENTS.CARD_CREATED, event);
|
||||||
|
this.logger.log(`Emitted CARD_CREATED event for card ${cardWithRelations.id}`);
|
||||||
|
|
||||||
|
return cardWithRelations;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getChildCards(guardianId: string): Promise<Card[]> {
|
async getChildCards(guardianId: string): Promise<Card[]> {
|
||||||
@ -61,7 +90,16 @@ export class CardService {
|
|||||||
parentCustomer.id,
|
parentCustomer.id,
|
||||||
);
|
);
|
||||||
|
|
||||||
return this.getCardById(createdCard.id);
|
const cardWithRelations = await this.getCardById(createdCard.id);
|
||||||
|
|
||||||
|
const event: ICardCreatedEvent = {
|
||||||
|
card: cardWithRelations,
|
||||||
|
timestamp: new Date(),
|
||||||
|
};
|
||||||
|
this.eventEmitter.emit(NOTIFICATION_EVENTS.CARD_CREATED, event);
|
||||||
|
this.logger.log(`Emitted CARD_CREATED event for child card ${cardWithRelations.id}`);
|
||||||
|
|
||||||
|
return cardWithRelations;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getCardByChildId(guardianId: string, childId: string): Promise<Card> {
|
async getCardByChildId(guardianId: string, childId: string): Promise<Card> {
|
||||||
@ -112,9 +150,24 @@ export class CardService {
|
|||||||
|
|
||||||
async updateCardStatus(body: AccountCardStatusChangedWebhookRequest) {
|
async updateCardStatus(body: AccountCardStatusChangedWebhookRequest) {
|
||||||
const card = await this.getCardByVpan(body.cardId);
|
const card = await this.getCardByVpan(body.cardId);
|
||||||
|
const previousStatus = card.status;
|
||||||
const { description, status } = CardStatusMapper[body.newStatus] || CardStatusMapper['99'];
|
const { description, status } = CardStatusMapper[body.newStatus] || CardStatusMapper['99'];
|
||||||
|
|
||||||
return this.cardRepository.updateCardStatus(card.id, status, description);
|
await this.cardRepository.updateCardStatus(card.id, status, description);
|
||||||
|
|
||||||
|
if (status === CardStatus.BLOCKED) {
|
||||||
|
const updatedCard = await this.getCardById(card.id);
|
||||||
|
const event: ICardBlockedEvent = {
|
||||||
|
card: updatedCard,
|
||||||
|
previousStatus,
|
||||||
|
blockReason: description,
|
||||||
|
timestamp: new Date(),
|
||||||
|
};
|
||||||
|
this.eventEmitter.emit(NOTIFICATION_EVENTS.CARD_BLOCKED, event);
|
||||||
|
this.logger.log(`Emitted CARD_BLOCKED event for card ${updatedCard.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { id: card.id, status, description };
|
||||||
}
|
}
|
||||||
|
|
||||||
async getEmbossingInformation(customerId: string) {
|
async getEmbossingInformation(customerId: string) {
|
||||||
@ -148,17 +201,79 @@ export class CardService {
|
|||||||
async transferToChild(juniorId: string, amount: number) {
|
async transferToChild(juniorId: string, amount: number) {
|
||||||
const card = await this.getCardByCustomerId(juniorId);
|
const card = await this.getCardByCustomerId(juniorId);
|
||||||
|
|
||||||
if (amount > card.account.balance - card.account.reservedBalance) {
|
this.logger.debug(`Transfer to child - juniorId: ${juniorId}, parentId: ${card.parentId}, cardId: ${card.id}`);
|
||||||
|
this.logger.debug(`Card account - balance: ${card.account.balance}, reserved: ${card.account.reservedBalance}`);
|
||||||
|
|
||||||
|
const fundingAccount = card.parentId
|
||||||
|
? await this.accountService.getAccountByCustomerId(card.parentId)
|
||||||
|
: card.account;
|
||||||
|
|
||||||
|
this.logger.debug(`Funding account - balance: ${fundingAccount.balance}, reserved: ${fundingAccount.reservedBalance}, available: ${fundingAccount.balance - fundingAccount.reservedBalance}`);
|
||||||
|
this.logger.debug(`Amount requested: ${amount}`);
|
||||||
|
|
||||||
|
if (amount > fundingAccount.balance - fundingAccount.reservedBalance) {
|
||||||
|
this.logger.error(`Insufficient balance - requested: ${amount}, available: ${fundingAccount.balance - fundingAccount.reservedBalance}`);
|
||||||
throw new BadRequestException('CARD.INSUFFICIENT_BALANCE');
|
throw new BadRequestException('CARD.INSUFFICIENT_BALANCE');
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalAmount = Decimal(amount).plus(card.limit);
|
// Validate card reference exists
|
||||||
await Promise.all([
|
if (!card.cardReference) {
|
||||||
this.neoleapService.updateCardControl(card.cardReference, finalAmount.toNumber()),
|
this.logger.error(`Card ${card.id} does not have a cardReference`);
|
||||||
this.updateCardLimit(card.id, finalAmount.toNumber()),
|
throw new BadRequestException('CARD.INVALID_CARD_REFERENCE');
|
||||||
this.accountService.increaseReservedBalance(card.account, amount),
|
}
|
||||||
this.transactionService.createInternalChildTransaction(card.id, amount),
|
|
||||||
]);
|
// Validate card limit is a valid number
|
||||||
|
const cardLimit = card.limit || 0;
|
||||||
|
if (isNaN(cardLimit) || cardLimit < 0) {
|
||||||
|
this.logger.error(`Card ${card.id} has invalid limit: ${cardLimit}`);
|
||||||
|
throw new BadRequestException('CARD.INVALID_CARD_LIMIT');
|
||||||
|
}
|
||||||
|
|
||||||
|
const finalAmount = Decimal(amount).plus(cardLimit);
|
||||||
|
const finalAmountNumber = finalAmount.toNumber();
|
||||||
|
|
||||||
|
// Validate final amount is positive
|
||||||
|
if (finalAmountNumber <= 0 || !isFinite(finalAmountNumber)) {
|
||||||
|
this.logger.error(`Invalid final amount calculated: ${finalAmountNumber} (amount: ${amount}, limit: ${cardLimit})`);
|
||||||
|
throw new BadRequestException('CARD.INVALID_AMOUNT');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(`Updating card control - cardReference: ${card.cardReference}, finalAmount: ${finalAmountNumber}`);
|
||||||
|
|
||||||
|
// Check if child and parent share the same account
|
||||||
|
const isSharedAccount = card.parentId && card.account.id === fundingAccount.id;
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Account structure - Child account: ${card.account.id}, Parent account: ${fundingAccount.id}, ` +
|
||||||
|
`Shared: ${isSharedAccount ? 'YES' : 'NO'}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// First, ensure all external operations succeed before creating transaction
|
||||||
|
if (isSharedAccount) {
|
||||||
|
// Shared account: Only update card limit and reserved balance
|
||||||
|
// Money is already in the shared account, just allocate it to the child
|
||||||
|
this.logger.debug(`Shared account detected - only updating card limit and reserved balance`);
|
||||||
|
await Promise.all([
|
||||||
|
this.neoleapService.updateCardControl(card.cardReference, finalAmountNumber),
|
||||||
|
this.updateCardLimit(card.id, finalAmountNumber),
|
||||||
|
this.accountService.increaseReservedBalance(fundingAccount, amount),
|
||||||
|
]);
|
||||||
|
} else {
|
||||||
|
// Separate accounts: Transfer money from parent to child
|
||||||
|
this.logger.debug(`Separate accounts - transferring money from parent to child`);
|
||||||
|
await Promise.all([
|
||||||
|
this.neoleapService.updateCardControl(card.cardReference, finalAmountNumber),
|
||||||
|
this.updateCardLimit(card.id, finalAmountNumber),
|
||||||
|
this.accountService.increaseReservedBalance(fundingAccount, amount),
|
||||||
|
// Increase child account balance
|
||||||
|
this.accountService.creditAccountBalance(card.account.accountReference, amount),
|
||||||
|
// Decrease parent account balance
|
||||||
|
this.accountService.decreaseAccountBalance(fundingAccount.accountReference, amount),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only create transaction and emit event after all operations succeed
|
||||||
|
await this.transactionService.createInternalChildTransaction(card.id, amount);
|
||||||
|
|
||||||
return finalAmount.toNumber();
|
return finalAmount.toNumber();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
import { forwardRef, Inject, Injectable, UnprocessableEntityException } from '@nestjs/common';
|
import { forwardRef, Inject, Injectable, UnprocessableEntityException } from '@nestjs/common';
|
||||||
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||||
import Decimal from 'decimal.js';
|
import Decimal from 'decimal.js';
|
||||||
import moment from 'moment';
|
import moment from 'moment';
|
||||||
import { Transactional } from 'typeorm-transactional';
|
import { Transactional } from 'typeorm-transactional';
|
||||||
@ -6,6 +7,8 @@ import {
|
|||||||
AccountTransactionWebhookRequest,
|
AccountTransactionWebhookRequest,
|
||||||
CardTransactionWebhookRequest,
|
CardTransactionWebhookRequest,
|
||||||
} from '~/common/modules/neoleap/dtos/requests';
|
} 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 { Transaction } from '../entities/transaction.entity';
|
||||||
import { CustomerType, TransactionType } from '../enums';
|
import { CustomerType, TransactionType } from '../enums';
|
||||||
import { TransactionRepository } from '../repositories/transaction.repository';
|
import { TransactionRepository } from '../repositories/transaction.repository';
|
||||||
@ -27,6 +30,7 @@ export class TransactionService {
|
|||||||
private readonly transactionRepository: TransactionRepository,
|
private readonly transactionRepository: TransactionRepository,
|
||||||
private readonly accountService: AccountService,
|
private readonly accountService: AccountService,
|
||||||
@Inject(forwardRef(() => CardService)) private readonly cardService: CardService,
|
@Inject(forwardRef(() => CardService)) private readonly cardService: CardService,
|
||||||
|
private readonly eventEmitter: EventEmitter2,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
@ -42,14 +46,31 @@ export class TransactionService {
|
|||||||
const total = new Decimal(body.transactionAmount).plus(body.billingAmount).plus(body.fees).plus(body.vatOnFees);
|
const total = new Decimal(body.transactionAmount).plus(body.billingAmount).plus(body.fees).plus(body.vatOnFees);
|
||||||
|
|
||||||
if (card.customerType === CustomerType.CHILD) {
|
if (card.customerType === CustomerType.CHILD) {
|
||||||
await Promise.all([
|
if (card.parentId) {
|
||||||
this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber()),
|
const parentAccount = await this.accountService.getAccountByCustomerId(card.parentId);
|
||||||
this.accountService.decrementReservedBalance(card.account, total.toNumber()),
|
await Promise.all([
|
||||||
]);
|
this.accountService.decreaseAccountBalance(parentAccount.accountReference, total.toNumber()),
|
||||||
|
this.accountService.decrementReservedBalance(parentAccount, total.toNumber()),
|
||||||
|
]);
|
||||||
|
} else {
|
||||||
|
await Promise.all([
|
||||||
|
this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber()),
|
||||||
|
this.accountService.decrementReservedBalance(card.account, total.toNumber()),
|
||||||
|
]);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
await this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber());
|
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;
|
return transaction;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,12 +87,44 @@ export class TransactionService {
|
|||||||
const transaction = await this.transactionRepository.createAccountTransaction(account, body);
|
const transaction = await this.transactionRepository.createAccountTransaction(account, body);
|
||||||
await this.accountService.creditAccountBalance(account.accountReference, body.amount);
|
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;
|
return transaction;
|
||||||
}
|
}
|
||||||
|
|
||||||
async createInternalChildTransaction(cardId: string, amount: number) {
|
async createInternalChildTransaction(cardId: string, amount: number) {
|
||||||
const card = await this.cardService.getCardById(cardId);
|
const card = await this.cardService.getCardById(cardId);
|
||||||
const transaction = await this.transactionRepository.createInternalChildTransaction(card, amount);
|
const transaction = await this.transactionRepository.createInternalChildTransaction(card, amount);
|
||||||
|
|
||||||
|
// Reload card to get updated account balance after the transfer
|
||||||
|
const cardWithUpdatedBalance = await this.cardService.getCardById(cardId);
|
||||||
|
|
||||||
|
const event: ITransactionCreatedEvent = {
|
||||||
|
transaction,
|
||||||
|
card: cardWithUpdatedBalance, // Use card with updated balance
|
||||||
|
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;
|
return transaction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -17,7 +17,6 @@ export const getKycCallbackMock = (nationalId: string) => {
|
|||||||
salaryMax: '1000',
|
salaryMax: '1000',
|
||||||
incomeSource: 'Salary',
|
incomeSource: 'Salary',
|
||||||
professionTitle: 'Software Engineer',
|
professionTitle: 'Software Engineer',
|
||||||
professionType: 'Full-Time',
|
|
||||||
isPep: 'N',
|
isPep: 'N',
|
||||||
country: '682',
|
country: '682',
|
||||||
region: 'Mecca',
|
region: 'Mecca',
|
||||||
|
|||||||
@ -1,129 +1,50 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { Expose } from 'class-transformer';
|
import { IsEnum, IsObject, IsString } from 'class-validator';
|
||||||
import { IsString } from 'class-validator';
|
|
||||||
export class KycWebhookRequest {
|
|
||||||
@Expose({ name: 'InstId' })
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ name: 'InstId', example: '1100' })
|
|
||||||
instId!: string;
|
|
||||||
|
|
||||||
@Expose()
|
export enum NeoleapKycWebhookStatus {
|
||||||
@IsString()
|
ONBOARDING_SUCCESS = 'ONBOARDING_SUCCESS',
|
||||||
@ApiProperty({ example: '3136fd60-3f89-4d24-a92f-b9c63a53807f' })
|
ONBOARDING_FAILURE = 'ONBOARDING_FAILURE',
|
||||||
transId!: string;
|
IN_PROGRESS = 'IN_PROGRESS',
|
||||||
|
}
|
||||||
@Expose()
|
|
||||||
@IsString()
|
class KycEntityDto {
|
||||||
@ApiProperty({ example: '20250807' })
|
@ApiProperty({ example: 'INDIVIDUAL', description: 'Entity type - INDIVIDUAL for KYC' })
|
||||||
date!: string;
|
@IsString()
|
||||||
|
type!: string;
|
||||||
@Expose()
|
|
||||||
@IsString()
|
@ApiProperty({ example: 'FIN-TECK-CUSTOMER-20393', description: 'Customer external ID from Neoleap' })
|
||||||
@ApiProperty({ example: '150000' })
|
@IsString()
|
||||||
time!: string;
|
externalId!: string;
|
||||||
|
}
|
||||||
@Expose()
|
|
||||||
@IsString()
|
export class KycWebhookRequest {
|
||||||
@ApiProperty({ example: 'SUCCESS' })
|
@ApiProperty({
|
||||||
status!: string;
|
example: '8a745b1b-1252-4921-a569-b3d4406c25fd',
|
||||||
|
description: 'Transaction ID, the same as returned from onboard API response'
|
||||||
@Expose()
|
})
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiProperty({ example: 'John' })
|
stateId!: string;
|
||||||
firstName!: string;
|
|
||||||
|
@ApiProperty({
|
||||||
@Expose()
|
example: '8a745b1b-1252-4921-a569-b3d4406c25fd',
|
||||||
@IsString()
|
description: 'Unique callback ID used as reference and for tracking'
|
||||||
@ApiProperty({ example: 'Doe' })
|
})
|
||||||
lastName!: string;
|
@IsString()
|
||||||
|
callbackId!: string;
|
||||||
@Expose()
|
|
||||||
@IsString()
|
@ApiProperty({ example: '1100', description: 'Fintech ID (1100 for ZOD)' })
|
||||||
@ApiProperty({ example: '19990107' })
|
@IsString()
|
||||||
dob!: string;
|
externalFintechId!: string;
|
||||||
|
|
||||||
@Expose()
|
@ApiProperty({ type: KycEntityDto })
|
||||||
@IsString()
|
@IsObject()
|
||||||
@ApiProperty({ example: '682' })
|
entity!: KycEntityDto;
|
||||||
nationality!: string;
|
|
||||||
|
@ApiProperty({
|
||||||
@Expose()
|
enum: NeoleapKycWebhookStatus,
|
||||||
@IsString()
|
example: NeoleapKycWebhookStatus.ONBOARDING_SUCCESS,
|
||||||
@ApiProperty({ example: 'M' })
|
description: 'Status of onboarding: ONBOARDING_SUCCESS or ONBOARDING_FAILURE'
|
||||||
gender!: string;
|
})
|
||||||
|
@IsEnum(NeoleapKycWebhookStatus)
|
||||||
@Expose()
|
status!: NeoleapKycWebhookStatus;
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: '20310917' })
|
|
||||||
nationalIdExpiry!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: '1250820840' })
|
|
||||||
nationalId!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: '+962798765432' })
|
|
||||||
mobile!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: '500' })
|
|
||||||
salaryMin!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: '1000' })
|
|
||||||
salaryMax!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'Salary' })
|
|
||||||
incomeSource!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'Software Engineer' })
|
|
||||||
professionTitle!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'Full-Time' })
|
|
||||||
professionType!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'N' })
|
|
||||||
isPep!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: '682' })
|
|
||||||
country!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'Mecca' })
|
|
||||||
region!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'At-Taif' })
|
|
||||||
city!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'Al-Hamra' })
|
|
||||||
neighborhood!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: 'Al-Masjid Al-Haram' })
|
|
||||||
street!: string;
|
|
||||||
|
|
||||||
@Expose()
|
|
||||||
@IsString()
|
|
||||||
@ApiProperty({ example: '123' })
|
|
||||||
building!: string;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -48,47 +48,109 @@ export class NeoLeapService {
|
|||||||
this.useKycMock = [true, 'true'].includes(this.configService.get<boolean>('USE_KYC_MOCK', true));
|
this.useKycMock = [true, 'true'].includes(this.configService.get<boolean>('USE_KYC_MOCK', true));
|
||||||
}
|
}
|
||||||
|
|
||||||
initiateKyc(customerId: string, body: InitiateKycRequestDto) {
|
async initiateKycOnboarding(dto: InitiateKycRequestDto) {
|
||||||
const responseKey = 'InitiateKycResponseDetails';
|
// Mock mode for development
|
||||||
|
|
||||||
if (this.useKycMock) {
|
if (this.useKycMock) {
|
||||||
const responseDto = plainToInstance(InitiateKycResponseDto, INITIATE_KYC_MOCK[responseKey], {
|
const mockResponse = {
|
||||||
excludeExtraneousValues: true,
|
externalCustomerId: `FIN-TECK-CUSTOMER-${Date.now()}`,
|
||||||
});
|
externalFintechId: '1100',
|
||||||
|
nafathRandomCode: '38',
|
||||||
|
stateId: uuid(),
|
||||||
|
status: 'IN_PROGRESS',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Trigger mock webhook after 7 seconds
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.httpService
|
this.httpService
|
||||||
.post(`${this.zodApiUrl}/neoleap-webhooks/kyc`, getKycCallbackMock(body.nationalId), {
|
.post(`${this.zodApiUrl}/neoleap-webhooks/kyc`, {
|
||||||
headers: {
|
stateId: mockResponse.stateId,
|
||||||
'Content-Type': 'application/json',
|
callbackId: uuid(),
|
||||||
|
externalFintechId: '1100',
|
||||||
|
entity: {
|
||||||
|
type: 'INDIVIDUAL',
|
||||||
|
externalId: mockResponse.externalCustomerId,
|
||||||
},
|
},
|
||||||
|
status: 'ONBOARDING_SUCCESS',
|
||||||
})
|
})
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: () => this.logger.log('Mock KYC webhook sent'),
|
next: () => this.logger.log('Mock KYC webhook sent successfully'),
|
||||||
error: (err) => console.error(err),
|
error: (err) => this.logger.error('Mock KYC webhook failed:', err.message),
|
||||||
});
|
});
|
||||||
}, 7000);
|
}, 7000);
|
||||||
|
|
||||||
return responseDto;
|
return mockResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Real API call to Neoleap
|
||||||
const payload = {
|
const payload = {
|
||||||
InitiateKycRequestDetails: {
|
poiNumber: dto.poiNumber,
|
||||||
CustomerIdentifier: {
|
poiType: dto.poiType,
|
||||||
InstitutionCode: this.institutionCode,
|
mobileNumber: dto.mobileNumber,
|
||||||
Id: customerId,
|
email: dto.email,
|
||||||
NationalId: body.nationalId,
|
dateOfBirth: dto.dateOfBirth,
|
||||||
|
jobSector: dto.jobSector,
|
||||||
|
employer: dto.employer,
|
||||||
|
incomeSource: dto.incomeSource,
|
||||||
|
jobCategory: dto.jobCategory,
|
||||||
|
incomeRange: dto.incomeRange,
|
||||||
|
// Use default address values for Neoleap KYC
|
||||||
|
address: {
|
||||||
|
national: {
|
||||||
|
buildingNumber: '1',
|
||||||
|
additionalNumber: '',
|
||||||
|
street: 'King Fahd Road',
|
||||||
|
streetEn: 'King Fahd Road',
|
||||||
|
city: 'Riyadh',
|
||||||
|
cityEn: 'Riyadh',
|
||||||
|
zipcode: '',
|
||||||
|
unitNumber: '',
|
||||||
|
district: 'Al Olaya',
|
||||||
|
districtEn: 'Al Olaya',
|
||||||
|
},
|
||||||
|
general: {
|
||||||
|
address: '1, King Fahd Road, Al Olaya, Riyadh, Riyadh',
|
||||||
|
website: '',
|
||||||
|
email: dto.email || '',
|
||||||
|
telephone1: dto.mobileNumber || '',
|
||||||
|
telephone2: '',
|
||||||
|
fax1: '',
|
||||||
|
fax2: '',
|
||||||
|
postalBox1: '',
|
||||||
|
postalBox2: '',
|
||||||
|
zipcode: '',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
RequestHeader: this.prepareHeaders('InitiateKyc'),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return this.sendRequestToNeoLeap<typeof payload, InitiateKycResponseDto>(
|
try {
|
||||||
'kyc/InitiateKyc',
|
const { data } = await this.httpService.axiosRef.post(
|
||||||
payload,
|
`${this.gatewayBaseUrl}/kyc/onboardCustomer`,
|
||||||
responseKey,
|
payload,
|
||||||
InitiateKycResponseDto,
|
{
|
||||||
);
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: this.apiKey,
|
||||||
|
'X-Request-id': uuid(),
|
||||||
|
'X-Session-Language': 'ar',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return data.data;
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error('Error initiating KYC:', error.response?.data || error.message);
|
||||||
|
|
||||||
|
// Handle specific Neoleap errors
|
||||||
|
if (error.response?.data?.errorCode === 'E810109') {
|
||||||
|
throw new BadRequestException('National ID is already registered with Neoleap');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.response?.data?.error === 'schema validation failed') {
|
||||||
|
throw new BadRequestException('Invalid data format for KYC verification');
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new InternalServerErrorException('Failed to initiate KYC verification');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
createApplication(customer: Customer) {
|
createApplication(customer: Customer) {
|
||||||
@ -124,7 +186,9 @@ export class NeoLeapService {
|
|||||||
},
|
},
|
||||||
BillingCycle: 'C1',
|
BillingCycle: 'C1',
|
||||||
},
|
},
|
||||||
ApplicationOtherInfo: {},
|
ApplicationOtherInfo: {
|
||||||
|
ExternalCorporateId: customer.neoleapExternalCustomerId,
|
||||||
|
},
|
||||||
ApplicationCustomerDetails: {
|
ApplicationCustomerDetails: {
|
||||||
FirstName: customer.firstName,
|
FirstName: customer.firstName,
|
||||||
LastName: customer.lastName,
|
LastName: customer.lastName,
|
||||||
@ -137,14 +201,14 @@ export class NeoLeapService {
|
|||||||
Title: customer.gender === Gender.MALE ? 'Mr' : 'Ms',
|
Title: customer.gender === Gender.MALE ? 'Mr' : 'Ms',
|
||||||
Gender: customer.gender === Gender.MALE ? 'M' : 'F',
|
Gender: customer.gender === Gender.MALE ? 'M' : 'F',
|
||||||
LocalizedDateOfBirth: moment(customer.dateOfBirth).format('YYYY-MM-DD'),
|
LocalizedDateOfBirth: moment(customer.dateOfBirth).format('YYYY-MM-DD'),
|
||||||
Nationality: CountriesNumericISO[customer.countryOfResidence],
|
Nationality: CountriesNumericISO[customer.countryOfResidence || 'SA'],
|
||||||
},
|
},
|
||||||
ApplicationAddress: {
|
ApplicationAddress: {
|
||||||
City: customer.city,
|
City: 'Riyadh',
|
||||||
Country: CountriesNumericISO[customer.country],
|
Country: CountriesNumericISO['SA'],
|
||||||
Region: customer.region,
|
Region: 'Riyadh',
|
||||||
AddressLine1: `${customer.street} ${customer.building}`,
|
AddressLine1: 'King Fahd Road 1',
|
||||||
AddressLine2: customer.neighborhood,
|
AddressLine2: 'Al Olaya',
|
||||||
AddressRole: 0,
|
AddressRole: 0,
|
||||||
Email: customer.user.email,
|
Email: customer.user.email,
|
||||||
Phone1: customer.user.phoneNumber,
|
Phone1: customer.user.phoneNumber,
|
||||||
@ -213,14 +277,14 @@ export class NeoLeapService {
|
|||||||
Title: parent.gender === Gender.MALE ? 'Mr' : 'Ms',
|
Title: parent.gender === Gender.MALE ? 'Mr' : 'Ms',
|
||||||
Gender: parent.gender === Gender.MALE ? 'M' : 'F',
|
Gender: parent.gender === Gender.MALE ? 'M' : 'F',
|
||||||
LocalizedDateOfBirth: moment(parent.dateOfBirth).format('YYYY-MM-DD'),
|
LocalizedDateOfBirth: moment(parent.dateOfBirth).format('YYYY-MM-DD'),
|
||||||
Nationality: CountriesNumericISO[parent.countryOfResidence],
|
Nationality: CountriesNumericISO[parent.countryOfResidence || 'SA'],
|
||||||
},
|
},
|
||||||
ApplicationAddress: {
|
ApplicationAddress: {
|
||||||
City: parent.city,
|
City: 'Riyadh',
|
||||||
Country: CountriesNumericISO[parent.country],
|
Country: CountriesNumericISO['SA'],
|
||||||
Region: parent.region,
|
Region: 'Riyadh',
|
||||||
AddressLine1: `${parent.street} ${parent.building}`,
|
AddressLine1: 'King Fahd Road 1',
|
||||||
AddressLine2: parent.neighborhood,
|
AddressLine2: 'Al Olaya',
|
||||||
AddressRole: 0,
|
AddressRole: 0,
|
||||||
Email: child.user.email,
|
Email: child.user.email,
|
||||||
Phone1: child.user.phoneNumber,
|
Phone1: child.user.phoneNumber,
|
||||||
@ -363,10 +427,18 @@ export class NeoLeapService {
|
|||||||
});
|
});
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
if (error.status === 400) {
|
if (error.status === 400) {
|
||||||
console.error('Error sending request to NeoLeap:', error);
|
const errorMessage = error.response?.data?.ResponseHeader?.ResponseDescription ||
|
||||||
throw new BadRequestException(error.response?.data?.ResponseHeader?.ResponseDescription || error.message);
|
error.response?.data?.message ||
|
||||||
|
error.message;
|
||||||
|
const errorCode = error.response?.data?.ResponseHeader?.ResponseCode || 'UNKNOWN';
|
||||||
|
this.logger.error(
|
||||||
|
`NeoLeap API returned 400 error for endpoint ${endpoint}. ` +
|
||||||
|
`Error Code: ${errorCode}, Message: ${errorMessage}. ` +
|
||||||
|
`Payload: ${JSON.stringify(payload)}`
|
||||||
|
);
|
||||||
|
throw new BadRequestException(errorMessage || 'Request failed with status code 400');
|
||||||
}
|
}
|
||||||
console.error('Error sending request to NeoLeap:', error);
|
this.logger.error(`Error sending request to NeoLeap endpoint ${endpoint}:`, error);
|
||||||
throw new InternalServerErrorException('Error communicating with NeoLeap service');
|
throw new InternalServerErrorException('Error communicating with NeoLeap service');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,37 @@
|
|||||||
|
/**
|
||||||
|
* 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',
|
||||||
|
|
||||||
|
// KYC Update events
|
||||||
|
KYC_APPROVED: 'notification.kyc.approved',
|
||||||
|
KYC_REJECTED: 'notification.kyc.rejected',
|
||||||
|
|
||||||
|
// Card Status events
|
||||||
|
CARD_CREATED: 'notification.card.created',
|
||||||
|
CARD_BLOCKED: 'notification.card.blocked',
|
||||||
|
CARD_REISSUED: 'notification.card.reissued',
|
||||||
|
|
||||||
|
// Profile Update events
|
||||||
|
PROFILE_UPDATED: 'notification.profile.updated',
|
||||||
|
|
||||||
|
// System Alert events
|
||||||
|
MAINTENANCE_ALERT: 'notification.system.maintenance',
|
||||||
|
TRANSACTION_FAILED: 'notification.system.transaction-failed',
|
||||||
|
SUSPICIOUS_LOGIN: 'notification.system.suspicious-login',
|
||||||
|
} 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';
|
||||||
|
|
||||||
@ -23,6 +23,17 @@ export class NotificationsResponseDto {
|
|||||||
this.title = notification.title;
|
this.title = notification.title;
|
||||||
this.body = notification.message;
|
this.body = notification.message;
|
||||||
this.status = notification.status!;
|
this.status = notification.status!;
|
||||||
this.createdAt = notification.createdAt;
|
|
||||||
|
// Use event timestamp from data if available, otherwise use notification creation time
|
||||||
|
// This ensures notifications show when the event occurred, not when notification was saved
|
||||||
|
// Note: Timestamps are stored in UTC. The client should convert to the user's local timezone.
|
||||||
|
if (notification.data?.timestamp) {
|
||||||
|
// Parse the ISO string timestamp (which is in UTC)
|
||||||
|
// The client should convert this to the user's local timezone based on their device settings
|
||||||
|
this.createdAt = new Date(notification.data.timestamp);
|
||||||
|
} else {
|
||||||
|
// Use notification creation time (also in UTC)
|
||||||
|
this.createdAt = notification.createdAt;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -36,6 +36,9 @@ export class Notification {
|
|||||||
@Column('uuid', { name: 'user_id', nullable: true })
|
@Column('uuid', { name: 'user_id', nullable: true })
|
||||||
userId!: string;
|
userId!: string;
|
||||||
|
|
||||||
|
@Column('jsonb', { name: 'data', nullable: true })
|
||||||
|
data?: Record<string, any>;
|
||||||
|
|
||||||
@ManyToOne(() => User, (user) => user.notifications, { onDelete: 'CASCADE', nullable: true })
|
@ManyToOne(() => User, (user) => user.notifications, { onDelete: 'CASCADE', nullable: true })
|
||||||
@JoinColumn({ name: 'user_id' })
|
@JoinColumn({ name: 'user_id' })
|
||||||
user!: User;
|
user!: User;
|
||||||
|
|||||||
@ -1,7 +1,67 @@
|
|||||||
export enum NotificationScope {
|
export enum NotificationScope {
|
||||||
|
// Existing scopes
|
||||||
USER_REGISTERED = 'USER_REGISTERED',
|
USER_REGISTERED = 'USER_REGISTERED',
|
||||||
TASK_COMPLETED = 'TASK_COMPLETED',
|
TASK_COMPLETED = 'TASK_COMPLETED',
|
||||||
GIFT_RECEIVED = 'GIFT_RECEIVED',
|
GIFT_RECEIVED = 'GIFT_RECEIVED',
|
||||||
OTP = 'OTP',
|
OTP = 'OTP',
|
||||||
USER_INVITED = 'USER_INVITED',
|
USER_INVITED = 'USER_INVITED',
|
||||||
|
|
||||||
|
// Transaction notifications - Top-up (external funds)
|
||||||
|
CHILD_TOP_UP = 'CHILD_TOP_UP',
|
||||||
|
PARENT_TOP_UP_CONFIRMATION = 'PARENT_TOP_UP_CONFIRMATION',
|
||||||
|
|
||||||
|
// Transaction notifications - Internal Transfer (parent to child)
|
||||||
|
CHILD_INTERNAL_TRANSFER = 'CHILD_INTERNAL_TRANSFER',
|
||||||
|
PARENT_INTERNAL_TRANSFER = 'PARENT_INTERNAL_TRANSFER',
|
||||||
|
|
||||||
|
// 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',
|
||||||
|
|
||||||
|
// KYC Update notifications
|
||||||
|
KYC_APPROVED = 'KYC_APPROVED',
|
||||||
|
KYC_REJECTED = 'KYC_REJECTED',
|
||||||
|
|
||||||
|
// Card Status notifications
|
||||||
|
CARD_CREATED = 'CARD_CREATED',
|
||||||
|
CARD_BLOCKED = 'CARD_BLOCKED',
|
||||||
|
CARD_REISSUED = 'CARD_REISSUED',
|
||||||
|
|
||||||
|
// Profile Update notifications
|
||||||
|
PROFILE_UPDATED = 'PROFILE_UPDATED',
|
||||||
|
|
||||||
|
// System Alert notifications
|
||||||
|
MAINTENANCE_ALERT = 'MAINTENANCE_ALERT',
|
||||||
|
TRANSACTION_FAILED = 'TRANSACTION_FAILED',
|
||||||
|
SUSPICIOUS_LOGIN = 'SUSPICIOUS_LOGIN',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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-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,221 @@
|
|||||||
|
import { Transaction } from '~/card/entities/transaction.entity';
|
||||||
|
import { Card } from '~/card/entities/card.entity';
|
||||||
|
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
|
||||||
|
import { Customer } from '~/customer/entities';
|
||||||
|
import { KycStatus } from '~/customer/enums';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for when KYC is approved
|
||||||
|
* Used to notify users when their KYC verification is approved
|
||||||
|
*/
|
||||||
|
export interface IKycApprovedEvent {
|
||||||
|
/** The customer whose KYC was approved */
|
||||||
|
customer: Customer;
|
||||||
|
|
||||||
|
/** Previous KYC status */
|
||||||
|
previousStatus: KycStatus;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for when KYC is rejected
|
||||||
|
* Used to notify users when their KYC verification is rejected
|
||||||
|
*/
|
||||||
|
export interface IKycRejectedEvent {
|
||||||
|
/** The customer whose KYC was rejected */
|
||||||
|
customer: Customer;
|
||||||
|
|
||||||
|
/** Previous KYC status */
|
||||||
|
previousStatus: KycStatus;
|
||||||
|
|
||||||
|
/** Rejection reason (if provided) */
|
||||||
|
rejectionReason?: string;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for when a card is created
|
||||||
|
* Used to notify users when their card is successfully created
|
||||||
|
*/
|
||||||
|
export interface ICardCreatedEvent {
|
||||||
|
/** The card that was created */
|
||||||
|
card: Card;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for when a card is blocked
|
||||||
|
* Used to notify users when their card is blocked
|
||||||
|
*/
|
||||||
|
export interface ICardBlockedEvent {
|
||||||
|
/** The card that was blocked */
|
||||||
|
card: Card;
|
||||||
|
|
||||||
|
/** Previous card status */
|
||||||
|
previousStatus: string;
|
||||||
|
|
||||||
|
/** Block reason/description */
|
||||||
|
blockReason?: string;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for when a card is reissued
|
||||||
|
* Used to notify users when their card is reissued
|
||||||
|
*/
|
||||||
|
export interface ICardReissuedEvent {
|
||||||
|
/** The new card that was issued */
|
||||||
|
card: Card;
|
||||||
|
|
||||||
|
/** The old card that was replaced */
|
||||||
|
oldCardId?: string;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for when a user profile is updated
|
||||||
|
* Used to notify users when their profile information is changed
|
||||||
|
*/
|
||||||
|
export interface IProfileUpdatedEvent {
|
||||||
|
/** The user whose profile was updated */
|
||||||
|
user: any;
|
||||||
|
|
||||||
|
/** Fields that were updated */
|
||||||
|
updatedFields: string[];
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for system maintenance alerts
|
||||||
|
* Used to notify users about scheduled or unscheduled maintenance
|
||||||
|
*/
|
||||||
|
export interface IMaintenanceAlertEvent {
|
||||||
|
/** User ID to notify (null for broadcast to all users) */
|
||||||
|
userId: string | null;
|
||||||
|
|
||||||
|
/** Maintenance message */
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
/** Scheduled start time */
|
||||||
|
startTime?: Date;
|
||||||
|
|
||||||
|
/** Scheduled end time */
|
||||||
|
endTime?: Date;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for failed transaction alerts
|
||||||
|
* Used to notify users when a transaction fails
|
||||||
|
*/
|
||||||
|
export interface ITransactionFailedEvent {
|
||||||
|
/** The user whose transaction failed */
|
||||||
|
userId: string;
|
||||||
|
|
||||||
|
/** Transaction details */
|
||||||
|
transactionId?: string;
|
||||||
|
|
||||||
|
/** Failure reason */
|
||||||
|
reason: string;
|
||||||
|
|
||||||
|
/** Transaction amount (if applicable) */
|
||||||
|
amount?: number;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event payload for suspicious login detection
|
||||||
|
* Used to notify users about suspicious login attempts
|
||||||
|
*/
|
||||||
|
export interface ISuspiciousLoginEvent {
|
||||||
|
/** The user whose account had suspicious activity */
|
||||||
|
userId: string;
|
||||||
|
|
||||||
|
/** IP address of the login attempt */
|
||||||
|
ipAddress?: string;
|
||||||
|
|
||||||
|
/** Location of the login attempt */
|
||||||
|
location?: string;
|
||||||
|
|
||||||
|
/** Device information */
|
||||||
|
device?: string;
|
||||||
|
|
||||||
|
/** When the event occurred */
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
@ -0,0 +1,162 @@
|
|||||||
|
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 { ICardBlockedEvent, ICardCreatedEvent } from '../interfaces/notification-events.interface';
|
||||||
|
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||||
|
import { User } from '~/user/entities';
|
||||||
|
import { UserLocale } from '~/core/enums/user-locale.enum';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CardNotificationListener {
|
||||||
|
private readonly logger = new Logger(CardNotificationListener.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly notificationFactory: NotificationFactory,
|
||||||
|
private readonly userService: UserService,
|
||||||
|
private readonly i18n: I18nService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.CARD_CREATED)
|
||||||
|
async handleCardCreated(event: ICardCreatedEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { card } = event;
|
||||||
|
const user = card?.customer?.user;
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
this.logger.warn(`No user found for card ${card.id}, skipping card created notification`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
const lastFourDigits = card.lastFourDigits;
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.CARD_CREATED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.CARD_CREATED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
lastFourDigits: lastFourDigits,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[CardNotificationListener] i18n error for user ${user.id}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'Card Created';
|
||||||
|
message = `Your card ending in ${lastFourDigits} has been created successfully. You can start using it once it's activated.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying user (user ${user.id}): Card created - ${lastFourDigits}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.CARD_CREATED,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
cardId: card.id,
|
||||||
|
lastFourDigits: lastFourDigits,
|
||||||
|
cardReference: card.cardReference,
|
||||||
|
status: card.status,
|
||||||
|
timestamp: event.timestamp.toISOString(),
|
||||||
|
action: 'VIEW_CARD',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${user.id} about card creation`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process card created notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.CARD_BLOCKED)
|
||||||
|
async handleCardBlocked(event: ICardBlockedEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { card, blockReason } = event;
|
||||||
|
const user = card?.customer?.user;
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
this.logger.warn(`No user found for card ${card.id}, skipping card blocked notification`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
const lastFourDigits = card.lastFourDigits;
|
||||||
|
const reason = blockReason || 'Card has been blocked';
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.CARD_BLOCKED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.CARD_BLOCKED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
lastFourDigits: lastFourDigits,
|
||||||
|
reason: reason,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[CardNotificationListener] i18n error for user ${user.id}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'Card Blocked';
|
||||||
|
message = `Your card ending in ${lastFourDigits} has been blocked. Reason: ${reason}. Please contact support for assistance.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying user (user ${user.id}): Card blocked - ${lastFourDigits}, reason: ${reason}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.CARD_BLOCKED,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
cardId: card.id,
|
||||||
|
lastFourDigits: lastFourDigits,
|
||||||
|
cardReference: card.cardReference,
|
||||||
|
status: card.status,
|
||||||
|
blockReason: reason,
|
||||||
|
timestamp: event.timestamp.toISOString(),
|
||||||
|
action: 'CONTACT_SUPPORT',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${user.id} about card being blocked`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process card blocked notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getUserPreferences(user: User): NotificationPreferences {
|
||||||
|
return {
|
||||||
|
isPushEnabled: user.isPushEnabled,
|
||||||
|
isEmailEnabled: user.isEmailEnabled,
|
||||||
|
isSmsEnabled: user.isSmsEnabled,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private getUserLocale(user: User): UserLocale {
|
||||||
|
return UserLocale.ENGLISH;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1 +1,7 @@
|
|||||||
export * from './notification-created.listener';
|
export * from './notification-created.listener';
|
||||||
|
export * from './transaction-notification.listener';
|
||||||
|
export * from './money-request-notification.listener';
|
||||||
|
export * from './kyc-notification.listener';
|
||||||
|
export * from './card-notification.listener';
|
||||||
|
export * from './profile-notification.listener';
|
||||||
|
export * from './system-alert-notification.listener';
|
||||||
@ -0,0 +1,233 @@
|
|||||||
|
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 {
|
||||||
|
IKycApprovedEvent,
|
||||||
|
IKycRejectedEvent,
|
||||||
|
} from '../interfaces/notification-events.interface';
|
||||||
|
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||||
|
import { User } from '~/user/entities';
|
||||||
|
import { UserLocale } from '~/core/enums/user-locale.enum';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* KycNotificationListener
|
||||||
|
*
|
||||||
|
* Handles notifications for KYC update events.
|
||||||
|
* Notifies users when their KYC verification is approved or rejected.
|
||||||
|
*
|
||||||
|
* Responsibilities:
|
||||||
|
* - Listen for KYC approval/rejection events
|
||||||
|
* - Determine notification recipient (the user whose KYC was updated)
|
||||||
|
* - Construct appropriate messages with rejection reason if applicable
|
||||||
|
* - Fetch user preferences
|
||||||
|
* - Call NotificationFactory to send
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class KycNotificationListener {
|
||||||
|
private readonly logger = new Logger(KycNotificationListener.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly notificationFactory: NotificationFactory,
|
||||||
|
private readonly userService: UserService,
|
||||||
|
private readonly i18n: I18nService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle KYC approved event
|
||||||
|
* Notifies user when their KYC verification is approved
|
||||||
|
*/
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.KYC_APPROVED)
|
||||||
|
async handleKycApproved(event: IKycApprovedEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { customer } = event;
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Processing KYC approved notification for customer ${customer.id}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notifyUserOfKycApproval(customer);
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`KYC approved notification processed successfully for customer ${customer.id}`
|
||||||
|
);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process KYC approved notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle KYC rejected event
|
||||||
|
* Notifies user when their KYC verification is rejected
|
||||||
|
*/
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.KYC_REJECTED)
|
||||||
|
async handleKycRejected(event: IKycRejectedEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { customer, rejectionReason } = event;
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Processing KYC rejected notification for customer ${customer.id} - Reason: ${rejectionReason || 'Not provided'}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notifyUserOfKycRejection(customer, rejectionReason);
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`KYC rejected notification processed successfully for customer ${customer.id}`
|
||||||
|
);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process KYC rejected notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify user when their KYC is approved
|
||||||
|
*/
|
||||||
|
private async notifyUserOfKycApproval(customer: any): Promise<void> {
|
||||||
|
try {
|
||||||
|
const user = customer?.user;
|
||||||
|
if (!user) {
|
||||||
|
this.logger.warn(`No user found for customer ${customer.id}, skipping notification`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.KYC_APPROVED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.KYC_APPROVED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[KycNotificationListener] i18n error for user ${user.id}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'KYC Verification Approved';
|
||||||
|
message = 'Your KYC verification has been approved. You can now use all features of the app.';
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying user (user ${user.id}): KYC approved`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.KYC_APPROVED,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
customerId: customer.id,
|
||||||
|
kycStatus: 'APPROVED',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
type: 'KYC_APPROVED',
|
||||||
|
action: 'VIEW_PROFILE',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${user.id} about KYC approval`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to notify user of KYC approval: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify user when their KYC is rejected
|
||||||
|
*/
|
||||||
|
private async notifyUserOfKycRejection(customer: any, rejectionReason?: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const user = customer?.user;
|
||||||
|
if (!user) {
|
||||||
|
this.logger.warn(`No user found for customer ${customer.id}, skipping notification`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
const reason = rejectionReason || customer.rejectionReason || 'KYC verification failed';
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.KYC_REJECTED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.KYC_REJECTED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
reason: reason,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[KycNotificationListener] i18n error for user ${user.id}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'KYC Verification Rejected';
|
||||||
|
message = `Your KYC verification has been rejected. Reason: ${reason}. Please review your information and try again.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying user (user ${user.id}): KYC rejected - ${reason}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.KYC_REJECTED,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
customerId: customer.id,
|
||||||
|
kycStatus: 'REJECTED',
|
||||||
|
rejectionReason: reason,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
type: 'KYC_REJECTED',
|
||||||
|
action: 'RETRY_KYC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${user.id} about KYC rejection`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to notify user of KYC 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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,335 @@
|
|||||||
|
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 {
|
||||||
|
IMoneyRequestApprovedEvent,
|
||||||
|
IMoneyRequestCreatedEvent,
|
||||||
|
IMoneyRequestDeclinedEvent,
|
||||||
|
} from '../interfaces/notification-events.interface';
|
||||||
|
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||||
|
import { User } from '~/user/entities';
|
||||||
|
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
|
||||||
|
import { UserLocale } from '~/core/enums/user-locale.enum';
|
||||||
|
import { formatCurrencyAmount, getCurrency } from '~/common/utils/currency.util';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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,
|
||||||
|
private readonly i18n: I18nService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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';
|
||||||
|
const accountCurrency = child?.customer?.cards?.[0]?.account?.currency;
|
||||||
|
const currency = getCurrency(accountCurrency, null, 'SAR');
|
||||||
|
const formattedAmount = formatCurrencyAmount(amount, currency);
|
||||||
|
|
||||||
|
const locale = this.getUserLocale(parentUser);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying parent (user ${parentUser.id}): ${childName} requested ${formattedAmount} ${currency} for ${reason}`
|
||||||
|
);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.MONEY_REQUEST_CREATED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.MONEY_REQUEST_CREATED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
childName: childName,
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
reason: reason,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[MoneyRequestNotificationListener] i18n error for parent ${parentUser.id}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'Money Request';
|
||||||
|
message = `${childName} has requested ${formattedAmount} ${currency} for ${reason}.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: parentUser.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.MONEY_REQUEST_CREATED,
|
||||||
|
preferences: this.getUserPreferences(parentUser),
|
||||||
|
data: {
|
||||||
|
moneyRequestId: moneyRequest.id,
|
||||||
|
childId: childUser?.id,
|
||||||
|
childName: childName,
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
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;
|
||||||
|
const accountCurrency = child?.customer?.cards?.[0]?.account?.currency;
|
||||||
|
const currency = getCurrency(accountCurrency, null, 'SAR');
|
||||||
|
const formattedAmount = formatCurrencyAmount(amount, currency);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying child (user ${childUser.id}): Money request of ${formattedAmount} ${currency} was approved`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: childUser.id,
|
||||||
|
title: 'Money Request Approved',
|
||||||
|
message: `Your request for ${formattedAmount} ${currency} 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: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
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 accountCurrency = child?.customer?.cards?.[0]?.account?.currency;
|
||||||
|
const currency = getCurrency(accountCurrency, null, 'SAR');
|
||||||
|
const formattedAmount = formatCurrencyAmount(amount, currency);
|
||||||
|
const reason = rejectionReason || 'No reason provided';
|
||||||
|
const locale = this.getUserLocale(childUser);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying child (user ${childUser.id}): Money request of ${formattedAmount} ${currency} was declined`
|
||||||
|
);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.MONEY_REQUEST_DECLINED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.MONEY_REQUEST_DECLINED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
reason: reason,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[MoneyRequestNotificationListener] i18n error for child ${childUser.id}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'Money Request Declined';
|
||||||
|
message = `Your request for ${formattedAmount} ${currency} has been declined. Reason: ${reason}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: childUser.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.MONEY_REQUEST_DECLINED,
|
||||||
|
preferences: this.getUserPreferences(childUser),
|
||||||
|
data: {
|
||||||
|
moneyRequestId: moneyRequest.id,
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,6 +6,7 @@ import { EventType, NotificationChannel, NotificationScope } from '~/common/modu
|
|||||||
import { FirebaseService, TwilioService } from '~/common/modules/notification/services';
|
import { FirebaseService, TwilioService } from '~/common/modules/notification/services';
|
||||||
import { IEventInterface } from '~/common/redis/interface';
|
import { IEventInterface } from '~/common/redis/interface';
|
||||||
import { DeviceService } from '~/user/services';
|
import { DeviceService } from '~/user/services';
|
||||||
|
import { UserService } from '~/user/services/user.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class NotificationCreatedListener {
|
export class NotificationCreatedListener {
|
||||||
@ -16,6 +17,7 @@ export class NotificationCreatedListener {
|
|||||||
private readonly deviceService: DeviceService,
|
private readonly deviceService: DeviceService,
|
||||||
private readonly mailerService: MailerService,
|
private readonly mailerService: MailerService,
|
||||||
private readonly firebaseService: FirebaseService,
|
private readonly firebaseService: FirebaseService,
|
||||||
|
private readonly userService: UserService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -31,7 +33,7 @@ export class NotificationCreatedListener {
|
|||||||
return this.sendSMS(event.recipient!, event.message);
|
return this.sendSMS(event.recipient!, event.message);
|
||||||
|
|
||||||
case NotificationChannel.PUSH:
|
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:
|
case NotificationChannel.EMAIL:
|
||||||
return this.sendEmail({
|
return this.sendEmail({
|
||||||
@ -54,15 +56,54 @@ export class NotificationCreatedListener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async sendPushNotification(userId: string, title: string, body: string) {
|
private async sendPushNotification(
|
||||||
this.logger.log(`Sending push notification to user ${userId}`);
|
userId: string,
|
||||||
const tokens = await this.deviceService.getTokens(userId);
|
title: string,
|
||||||
|
body: string,
|
||||||
|
data?: Record<string, any>,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
// Check if user has push notifications enabled
|
||||||
|
const user = await this.userService.findUser({ id: userId });
|
||||||
|
if (!user) {
|
||||||
|
this.logger.warn(`User ${userId} not found, skipping push notification`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!tokens.length) {
|
if (!user.isPushEnabled) {
|
||||||
this.logger.log(`No device tokens found for user ${userId}, but notification was created in the DB.`);
|
this.logger.log(
|
||||||
return;
|
`Push notifications disabled for user ${userId}, notification saved to DB but push not sent`
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(`Sending push notification to user ${userId}`);
|
||||||
|
const tokens = await this.deviceService.getTokens(userId);
|
||||||
|
|
||||||
|
if (!tokens.length) {
|
||||||
|
this.logger.log(`No device tokens found for user ${userId}, but notification was created in the DB.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to send push notification to user ${userId}: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
// Don't throw - notification is already saved to DB
|
||||||
}
|
}
|
||||||
return this.firebaseService.sendNotification(tokens, title, body);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async sendSMS(to: string, body: string) {
|
private async sendSMS(to: string, body: string) {
|
||||||
|
|||||||
@ -0,0 +1,149 @@
|
|||||||
|
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 { IProfileUpdatedEvent } from '../interfaces/notification-events.interface';
|
||||||
|
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||||
|
import { User } from '~/user/entities';
|
||||||
|
import { UserLocale } from '~/core/enums/user-locale.enum';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ProfileNotificationListener {
|
||||||
|
private readonly logger = new Logger(ProfileNotificationListener.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly notificationFactory: NotificationFactory,
|
||||||
|
private readonly userService: UserService,
|
||||||
|
private readonly i18n: I18nService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.PROFILE_UPDATED)
|
||||||
|
async handleProfileUpdated(event: IProfileUpdatedEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { user, updatedFields } = event;
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Processing profile updated notification for user ${user.id} - Updated fields: ${updatedFields.join(', ')}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notifyUserOfProfileUpdate(user, updatedFields);
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Profile updated notification processed successfully for user ${user.id}`
|
||||||
|
);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process profile updated notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async notifyUserOfProfileUpdate(user: any, updatedFields: string[]): Promise<void> {
|
||||||
|
try {
|
||||||
|
if (!user) {
|
||||||
|
this.logger.warn(`No user found, skipping profile update notification`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
const isEmailUpdate = updatedFields.includes('email');
|
||||||
|
const isPasswordUpdate = updatedFields.includes('password');
|
||||||
|
const isProfilePictureUpdate = updatedFields.includes('profilePictureId');
|
||||||
|
const isNameUpdate = updatedFields.includes('firstName') || updatedFields.includes('lastName');
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isEmailUpdate) {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.PROFILE_EMAIL_UPDATED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.PROFILE_EMAIL_UPDATED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
email: user.email || 'your email',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else if (isPasswordUpdate) {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.PROFILE_PASSWORD_UPDATED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.PROFILE_PASSWORD_UPDATED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
});
|
||||||
|
} else if (isProfilePictureUpdate) {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.PROFILE_PICTURE_UPDATED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.PROFILE_PICTURE_UPDATED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
});
|
||||||
|
} else if (isNameUpdate) {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.PROFILE_NAME_UPDATED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.PROFILE_NAME_UPDATED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.PROFILE_UPDATED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.PROFILE_UPDATED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
fields: updatedFields.join(', '),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[ProfileNotificationListener] i18n error for user ${user.id}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isEmailUpdate) {
|
||||||
|
title = 'Email Updated';
|
||||||
|
message = `Your email has been updated to ${user.email || 'a new email'}. Please verify your new email address.`;
|
||||||
|
} else if (isPasswordUpdate) {
|
||||||
|
title = 'Password Updated';
|
||||||
|
message = 'Your password has been successfully updated. If you did not make this change, please contact support immediately.';
|
||||||
|
} else {
|
||||||
|
title = 'Profile Updated';
|
||||||
|
message = `Your profile has been updated. Changes: ${updatedFields.join(', ')}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying user (user ${user.id}): Profile updated - ${updatedFields.join(', ')}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.PROFILE_UPDATED,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
updatedFields: updatedFields,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
type: 'PROFILE_UPDATE',
|
||||||
|
action: 'VIEW_PROFILE',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${user.id} about profile update`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to notify user of profile update: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getUserPreferences(user: User): NotificationPreferences {
|
||||||
|
return {
|
||||||
|
isPushEnabled: user.isPushEnabled,
|
||||||
|
isEmailEnabled: user.isEmailEnabled,
|
||||||
|
isSmsEnabled: user.isSmsEnabled,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private getUserLocale(user: User): UserLocale {
|
||||||
|
return UserLocale.ENGLISH;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,282 @@
|
|||||||
|
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 {
|
||||||
|
IMaintenanceAlertEvent,
|
||||||
|
ISuspiciousLoginEvent,
|
||||||
|
ITransactionFailedEvent,
|
||||||
|
} from '../interfaces/notification-events.interface';
|
||||||
|
import { NotificationScope } from '../enums/notification-scope.enum';
|
||||||
|
import { User } from '~/user/entities';
|
||||||
|
import { UserLocale } from '~/core/enums/user-locale.enum';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SystemAlertNotificationListener {
|
||||||
|
private readonly logger = new Logger(SystemAlertNotificationListener.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly notificationFactory: NotificationFactory,
|
||||||
|
private readonly userService: UserService,
|
||||||
|
private readonly i18n: I18nService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.MAINTENANCE_ALERT)
|
||||||
|
async handleMaintenanceAlert(event: IMaintenanceAlertEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { userId, message, startTime, endTime } = event;
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Processing maintenance alert notification - User: ${userId || 'ALL'}, Message: ${message}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (userId) {
|
||||||
|
await this.notifyUserOfMaintenance(userId, message, startTime, endTime);
|
||||||
|
} else {
|
||||||
|
this.logger.warn('Broadcast maintenance alerts to all users not yet implemented');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(`Maintenance alert notification processed successfully`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process maintenance alert notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.TRANSACTION_FAILED)
|
||||||
|
async handleTransactionFailed(event: ITransactionFailedEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { userId, transactionId, reason, amount } = event;
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Processing transaction failed notification for user ${userId} - Transaction: ${transactionId}, Reason: ${reason}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notifyUserOfTransactionFailure(userId, transactionId, reason, amount);
|
||||||
|
|
||||||
|
this.logger.log(`Transaction failed notification processed successfully for user ${userId}`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process transaction failed notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OnEvent(NOTIFICATION_EVENTS.SUSPICIOUS_LOGIN)
|
||||||
|
async handleSuspiciousLogin(event: ISuspiciousLoginEvent): Promise<void> {
|
||||||
|
try {
|
||||||
|
const { userId, ipAddress, location, device } = event;
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Processing suspicious login notification for user ${userId} - IP: ${ipAddress}, Location: ${location}`
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.notifyUserOfSuspiciousLogin(userId, ipAddress, location, device);
|
||||||
|
|
||||||
|
this.logger.log(`Suspicious login notification processed successfully for user ${userId}`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to process suspicious login notification: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async notifyUserOfMaintenance(
|
||||||
|
userId: string,
|
||||||
|
message: string,
|
||||||
|
startTime?: Date,
|
||||||
|
endTime?: Date,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const user = await this.userService.findUserOrThrow({ id: userId });
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let notificationMessage: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.MAINTENANCE_ALERT_TITLE', { lang: locale });
|
||||||
|
notificationMessage = this.i18n.t('app.NOTIFICATION.MAINTENANCE_ALERT_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
message: message,
|
||||||
|
startTime: startTime ? startTime.toLocaleString() : '',
|
||||||
|
endTime: endTime ? endTime.toLocaleString() : '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[SystemAlertNotificationListener] i18n error for user ${userId}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'Scheduled Maintenance';
|
||||||
|
notificationMessage = message || 'The system will be under maintenance. Please check back later.';
|
||||||
|
if (startTime && endTime) {
|
||||||
|
notificationMessage += ` Scheduled from ${startTime.toLocaleString()} to ${endTime.toLocaleString()}.`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message: notificationMessage,
|
||||||
|
scope: NotificationScope.MAINTENANCE_ALERT,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
message: message,
|
||||||
|
startTime: startTime?.toISOString(),
|
||||||
|
endTime: endTime?.toISOString(),
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
type: 'MAINTENANCE',
|
||||||
|
action: 'VIEW_STATUS',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${userId} about maintenance`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to notify user of maintenance: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async notifyUserOfTransactionFailure(
|
||||||
|
userId: string,
|
||||||
|
transactionId: string | undefined,
|
||||||
|
reason: string,
|
||||||
|
amount?: number,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const user = await this.userService.findUserOrThrow({ id: userId });
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.TRANSACTION_FAILED_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.TRANSACTION_FAILED_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
reason: reason,
|
||||||
|
amount: amount ? amount.toString() : '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[SystemAlertNotificationListener] i18n error for user ${userId}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'Transaction Failed';
|
||||||
|
message = `Your transaction could not be completed. Reason: ${reason}.`;
|
||||||
|
if (amount) {
|
||||||
|
message += ` Amount: ${amount}`;
|
||||||
|
}
|
||||||
|
message += ' Please try again or contact support if the issue persists.';
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.TRANSACTION_FAILED,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
transactionId: transactionId,
|
||||||
|
reason: reason,
|
||||||
|
amount: amount,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
type: 'TRANSACTION_FAILED',
|
||||||
|
action: 'RETRY_TRANSACTION',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${userId} about failed transaction`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to notify user of transaction failure: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async notifyUserOfSuspiciousLogin(
|
||||||
|
userId: string,
|
||||||
|
ipAddress?: string,
|
||||||
|
location?: string,
|
||||||
|
device?: string,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const user = await this.userService.findUserOrThrow({ id: userId });
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.SUSPICIOUS_LOGIN_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.SUSPICIOUS_LOGIN_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
location: location || 'unknown location',
|
||||||
|
device: device || 'unknown device',
|
||||||
|
ipAddress: ipAddress || 'unknown IP',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[SystemAlertNotificationListener] i18n error for user ${userId}: ${i18nError?.message || 'Unknown i18n error'}. Falling back to English.`,
|
||||||
|
i18nError?.stack
|
||||||
|
);
|
||||||
|
title = 'Suspicious Login Detected';
|
||||||
|
message = `We detected a login attempt from ${location || 'an unknown location'} (${ipAddress || 'unknown IP'})`;
|
||||||
|
if (device) {
|
||||||
|
message += ` using ${device}`;
|
||||||
|
}
|
||||||
|
message += '. If this was not you, please change your password immediately and contact support.';
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: user.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.SUSPICIOUS_LOGIN,
|
||||||
|
preferences: this.getUserPreferences(user),
|
||||||
|
data: {
|
||||||
|
ipAddress: ipAddress,
|
||||||
|
location: location,
|
||||||
|
device: device,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
type: 'SUSPICIOUS_LOGIN',
|
||||||
|
action: 'CHANGE_PASSWORD',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`✅ Notified user ${userId} about suspicious login`);
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to notify user of suspicious login: ${error?.message || 'Unknown error'}`,
|
||||||
|
error?.stack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getUserPreferences(user: User): NotificationPreferences {
|
||||||
|
return {
|
||||||
|
isPushEnabled: user.isPushEnabled,
|
||||||
|
isEmailEnabled: user.isEmailEnabled,
|
||||||
|
isSmsEnabled: user.isSmsEnabled,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private getUserLocale(user: User): UserLocale {
|
||||||
|
return UserLocale.ENGLISH;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,668 @@
|
|||||||
|
import { forwardRef, Inject, 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 { AccountService } from '~/card/services/account.service';
|
||||||
|
import { CardService } from '~/card/services/card.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';
|
||||||
|
import { formatCurrencyAmount, getCurrency, numericToCurrencyCode } from '~/common/utils/currency.util';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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,
|
||||||
|
@Inject(forwardRef(() => AccountService))
|
||||||
|
private readonly accountService: AccountService,
|
||||||
|
@Inject(forwardRef(() => CardService))
|
||||||
|
private readonly cardService: CardService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine scope: internal transfer (parent to child) vs external top-up
|
||||||
|
let scope: NotificationScope;
|
||||||
|
if (isTopUp) {
|
||||||
|
scope = isChildSpending
|
||||||
|
? NotificationScope.CHILD_INTERNAL_TRANSFER // Parent transferring to child
|
||||||
|
: NotificationScope.CHILD_TOP_UP; // External top-up
|
||||||
|
} else {
|
||||||
|
scope = NotificationScope.CHILD_SPENDING;
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = this.getUserLocale(user);
|
||||||
|
const amount = transaction.transactionAmount;
|
||||||
|
const merchant = transaction.merchantName || 'merchant';
|
||||||
|
|
||||||
|
// For child notifications, show the appropriate balance based on account structure
|
||||||
|
let balance = 0;
|
||||||
|
let accountCurrency: string | undefined;
|
||||||
|
|
||||||
|
if (isTopUp && isChildSpending) {
|
||||||
|
// Internal transfer: For shared accounts, show card limit (child's spending power)
|
||||||
|
// For separate accounts, show child's account balance
|
||||||
|
try {
|
||||||
|
// Reload card to get updated data
|
||||||
|
const cardWithUpdatedBalance = await this.cardService.getCardById(card.id);
|
||||||
|
|
||||||
|
// Check if child has parent (shared account scenario)
|
||||||
|
if (cardWithUpdatedBalance.parentId) {
|
||||||
|
// Likely shared account - use card limit as the child's "balance"
|
||||||
|
balance = cardWithUpdatedBalance.limit || card.limit || 0;
|
||||||
|
accountCurrency = cardWithUpdatedBalance.account?.currency || card.account?.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Child Internal Transfer] Shared account - using card limit: ${balance} ${accountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Separate account - use child's account balance
|
||||||
|
if (cardWithUpdatedBalance?.account?.accountReference) {
|
||||||
|
const account = await this.accountService.getAccountByReferenceNumber(
|
||||||
|
cardWithUpdatedBalance.account.accountReference
|
||||||
|
);
|
||||||
|
balance = account.balance;
|
||||||
|
accountCurrency = account.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Child Internal Transfer] Separate account - using account balance: ${balance} ${accountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
balance = cardWithUpdatedBalance.account?.balance || card.account?.balance || 0;
|
||||||
|
accountCurrency = cardWithUpdatedBalance.account?.currency || card.account?.currency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.warn(
|
||||||
|
`[Child Internal Transfer] Could not fetch balance: ${error?.message}. Using card limit.`
|
||||||
|
);
|
||||||
|
balance = card.limit || 0;
|
||||||
|
accountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
} else if (isTopUp) {
|
||||||
|
// External top-up: show child's account balance
|
||||||
|
try {
|
||||||
|
const cardWithUpdatedBalance = await this.cardService.getCardById(card.id);
|
||||||
|
if (cardWithUpdatedBalance?.account?.accountReference) {
|
||||||
|
const account = await this.accountService.getAccountByReferenceNumber(
|
||||||
|
cardWithUpdatedBalance.account.accountReference
|
||||||
|
);
|
||||||
|
balance = account.balance;
|
||||||
|
accountCurrency = account.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Child Top-Up Notification] Fetched account by reference - balance: ${balance} ${accountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
balance = cardWithUpdatedBalance.account?.balance || card.account?.balance || 0;
|
||||||
|
accountCurrency = cardWithUpdatedBalance.account?.currency || card.account?.currency;
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.warn(
|
||||||
|
`[Child Top-Up Notification] Could not fetch account: ${error?.message}. Using card balance.`
|
||||||
|
);
|
||||||
|
balance = card.account?.balance || 0;
|
||||||
|
accountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// For spending: show account balance
|
||||||
|
try {
|
||||||
|
// Reload card to get account reference
|
||||||
|
const cardWithUpdatedBalance = await this.cardService.getCardById(card.id);
|
||||||
|
if (cardWithUpdatedBalance?.account?.accountReference) {
|
||||||
|
// Fetch by reference number to get fresh balance from database
|
||||||
|
const account = await this.accountService.getAccountByReferenceNumber(
|
||||||
|
cardWithUpdatedBalance.account.accountReference
|
||||||
|
);
|
||||||
|
balance = account.balance;
|
||||||
|
accountCurrency = account.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Child Spending Notification] Fetched account by reference - balance: ${balance} ${accountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Fallback: use card's account balance
|
||||||
|
balance = cardWithUpdatedBalance.account?.balance || card.account?.balance || 0;
|
||||||
|
accountCurrency = cardWithUpdatedBalance.account?.currency || card.account?.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Child Spending Notification] Using card account balance - balance: ${balance} ${accountCurrency}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.warn(
|
||||||
|
`[Child Spending Notification] Could not fetch account by reference: ${error?.message}. Using card account balance.`
|
||||||
|
);
|
||||||
|
// Fallback: use card's account balance
|
||||||
|
balance = card.account?.balance || 0;
|
||||||
|
accountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const currency = getCurrency(
|
||||||
|
accountCurrency,
|
||||||
|
transaction.transactionCurrency,
|
||||||
|
'SAR'
|
||||||
|
);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`[Child Notification] Account currency: ${accountCurrency}, Transaction currency: ${transaction.transactionCurrency}, Final currency: ${currency}, Balance: ${balance}, Amount: ${amount}`
|
||||||
|
);
|
||||||
|
|
||||||
|
const formattedAmount = formatCurrencyAmount(amount, currency);
|
||||||
|
const formattedBalance = formatCurrencyAmount(balance, currency);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isTopUp) {
|
||||||
|
// Internal transfer or external top-up
|
||||||
|
const titleKey = isChildSpending
|
||||||
|
? 'app.NOTIFICATION.CHILD_INTERNAL_TRANSFER_TITLE'
|
||||||
|
: 'app.NOTIFICATION.CHILD_TOP_UP_TITLE';
|
||||||
|
const messageKey = isChildSpending
|
||||||
|
? 'app.NOTIFICATION.CHILD_INTERNAL_TRANSFER_MESSAGE'
|
||||||
|
: 'app.NOTIFICATION.CHILD_TOP_UP_MESSAGE';
|
||||||
|
|
||||||
|
title = this.i18n.t(titleKey, { lang: locale });
|
||||||
|
message = this.i18n.t(messageKey, {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
balance: formattedBalance,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Spending
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.CHILD_SPENDING_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.CHILD_SPENDING_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
merchant: merchant,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} 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 ? 'Funds Credited' : 'Purchase Successful';
|
||||||
|
message = isTopUp
|
||||||
|
? `${formattedAmount} ${currency} has been added to your card. Total balance: ${formattedBalance} ${currency}`
|
||||||
|
: `You spent ${formattedAmount} ${currency} at ${merchant}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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: formattedAmount,
|
||||||
|
currency: currency, // ISO currency code (SAR, USD, etc.)
|
||||||
|
merchant: merchant,
|
||||||
|
merchantCategory: transaction.merchantCategoryCode || 'OTHER',
|
||||||
|
balance: formattedBalance,
|
||||||
|
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';
|
||||||
|
|
||||||
|
// Get parent's available balance (balance - reserved_balance) - reload to get fresh balance
|
||||||
|
let parentAccountBalance = 0;
|
||||||
|
let parentAccountReservedBalance = 0;
|
||||||
|
let parentAccountCurrency: string | undefined;
|
||||||
|
let availableBalance = 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (card.parentId) {
|
||||||
|
// Get parent's card to access their account reference
|
||||||
|
const parentCard = await this.cardService.getCardByCustomerId(card.parentId);
|
||||||
|
if (parentCard?.account?.accountReference) {
|
||||||
|
// Fetch by reference number to get fresh balance from database
|
||||||
|
const parentAccount = await this.accountService.getAccountByReferenceNumber(
|
||||||
|
parentCard.account.accountReference
|
||||||
|
);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Spending] Fetched parent account by reference - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Fallback: try by customer ID
|
||||||
|
const parentAccount = await this.accountService.getAccountByCustomerId(card.parentId);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Spending] Fetched parent account by customer ID - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const parentCustomer = customer?.junior?.guardian?.customer;
|
||||||
|
if (parentCustomer?.id) {
|
||||||
|
try {
|
||||||
|
const parentCard = await this.cardService.getCardByCustomerId(parentCustomer.id);
|
||||||
|
if (parentCard?.account?.accountReference) {
|
||||||
|
const parentAccount = await this.accountService.getAccountByReferenceNumber(
|
||||||
|
parentCard.account.accountReference
|
||||||
|
);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Spending] Fetched parent account via customer relation (by reference) - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const parentAccount = await this.accountService.getAccountByCustomerId(parentCustomer.id);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Spending] Fetched parent account via customer relation - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.warn(
|
||||||
|
`[Parent Spending] Could not fetch parent account via customer: ${error?.message}. Using child account balance as fallback.`
|
||||||
|
);
|
||||||
|
availableBalance = card.account?.balance || 0;
|
||||||
|
parentAccountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
availableBalance = card.account?.balance || 0;
|
||||||
|
parentAccountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.warn(`[Parent Spending] Could not fetch parent account: ${error?.message}, using child account balance as fallback`);
|
||||||
|
availableBalance = card.account?.balance || 0;
|
||||||
|
parentAccountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
|
||||||
|
const accountCurrency = parentAccountCurrency || card.account?.currency;
|
||||||
|
const currency = getCurrency(
|
||||||
|
accountCurrency,
|
||||||
|
transaction.transactionCurrency,
|
||||||
|
'SAR'
|
||||||
|
);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Spending Notification] Parent account currency: ${parentAccountCurrency}, Account currency: ${accountCurrency}, Transaction currency: ${transaction.transactionCurrency}, Final currency: ${currency}, Parent available balance: ${availableBalance}, Amount: ${amount}`
|
||||||
|
);
|
||||||
|
|
||||||
|
const formattedAmount = formatCurrencyAmount(amount, currency);
|
||||||
|
// Use available balance for parent spending notification
|
||||||
|
const formattedBalance = formatCurrencyAmount(availableBalance, currency);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying parent (user ${parentUser.id}): ${childName} spent ${formattedAmount} ${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: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
merchant: merchant,
|
||||||
|
balance: formattedBalance,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
console.error(`[TransactionNotificationListener] i18n error in parent spending:`, i18nError);
|
||||||
|
this.logger.error(`i18n translation failed: ${i18nError?.message}`, i18nError?.stack);
|
||||||
|
title = 'Spending Alert';
|
||||||
|
message = `${childName} spent ${formattedAmount} ${currency} at ${merchant}. Remaining balance: ${formattedBalance} ${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: formattedAmount, // Use formatted amount instead of raw amount
|
||||||
|
currency: currency, // ISO currency code (SAR, USD, etc.)
|
||||||
|
merchant: merchant,
|
||||||
|
merchantCategory: transaction.merchantCategoryCode || 'OTHER',
|
||||||
|
balance: formattedBalance,
|
||||||
|
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 transfer money to their child's card (internal transfer)
|
||||||
|
* 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;
|
||||||
|
|
||||||
|
// Fetch parent account by reference number to get fresh balance (bypasses entity cache)
|
||||||
|
// For parent notification, show available_balance = balance - reserved_balance
|
||||||
|
let parentAccountBalance = 0;
|
||||||
|
let parentAccountReservedBalance = 0;
|
||||||
|
let parentAccountCurrency: string | undefined;
|
||||||
|
let availableBalance = 0;
|
||||||
|
|
||||||
|
if (card.parentId) {
|
||||||
|
try {
|
||||||
|
// Get parent's card to access their account reference
|
||||||
|
// card.parentId is the parent's CUSTOMER ID
|
||||||
|
const parentCard = await this.cardService.getCardByCustomerId(card.parentId);
|
||||||
|
if (parentCard?.account?.accountReference) {
|
||||||
|
// Fetch by reference number to get fresh balance from database
|
||||||
|
const parentAccount = await this.accountService.getAccountByReferenceNumber(
|
||||||
|
parentCard.account.accountReference
|
||||||
|
);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Top-Up] Fetched parent account by reference - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Fallback: try by customer ID
|
||||||
|
const parentAccount = await this.accountService.getAccountByCustomerId(card.parentId);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Top-Up] Fetched parent account by customer ID - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.warn(
|
||||||
|
`[Parent Top-Up] Could not fetch parent account for customer ${card.parentId}: ${error?.message}. Using child account balance as fallback.`
|
||||||
|
);
|
||||||
|
availableBalance = card.account?.balance || 0;
|
||||||
|
parentAccountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// If no parentId, try via customer relation
|
||||||
|
const parentCustomer = customer?.junior?.guardian?.customer;
|
||||||
|
if (parentCustomer?.id) {
|
||||||
|
try {
|
||||||
|
const parentCard = await this.cardService.getCardByCustomerId(parentCustomer.id);
|
||||||
|
if (parentCard?.account?.accountReference) {
|
||||||
|
const parentAccount = await this.accountService.getAccountByReferenceNumber(
|
||||||
|
parentCard.account.accountReference
|
||||||
|
);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Top-Up] Fetched parent account via customer relation (by reference) - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const parentAccount = await this.accountService.getAccountByCustomerId(parentCustomer.id);
|
||||||
|
parentAccountBalance = parentAccount.balance;
|
||||||
|
parentAccountReservedBalance = parentAccount.reservedBalance;
|
||||||
|
availableBalance = parentAccountBalance - parentAccountReservedBalance;
|
||||||
|
parentAccountCurrency = parentAccount.currency;
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Top-Up] Fetched parent account via customer relation - balance: ${parentAccountBalance}, reserved: ${parentAccountReservedBalance}, available: ${availableBalance} ${parentAccountCurrency}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
this.logger.warn(
|
||||||
|
`[Parent Top-Up] Could not fetch parent account via customer: ${error?.message}. Using child account balance as fallback.`
|
||||||
|
);
|
||||||
|
availableBalance = card.account?.balance || 0;
|
||||||
|
parentAccountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
availableBalance = card.account?.balance || 0;
|
||||||
|
parentAccountCurrency = card.account?.currency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use available_balance for parent notification (balance - reserved_balance)
|
||||||
|
const balance = availableBalance;
|
||||||
|
const accountCurrency = parentAccountCurrency;
|
||||||
|
const currency = getCurrency(
|
||||||
|
accountCurrency,
|
||||||
|
transaction.transactionCurrency,
|
||||||
|
);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`[Parent Top-Up Notification] Parent account currency: ${parentAccountCurrency}, Account currency: ${accountCurrency}, Transaction currency: ${transaction.transactionCurrency}, Final currency: ${currency}, Parent balance: ${balance}, Amount: ${amount}`
|
||||||
|
);
|
||||||
|
|
||||||
|
const formattedAmount = formatCurrencyAmount(amount, currency);
|
||||||
|
const formattedBalance = formatCurrencyAmount(balance, currency);
|
||||||
|
|
||||||
|
this.logger.debug(
|
||||||
|
`Notifying parent (user ${parentUser.id}): Transferred ${formattedAmount} ${currency} to ${childName}, child balance: ${formattedBalance} ${currency}`
|
||||||
|
);
|
||||||
|
|
||||||
|
let title: string;
|
||||||
|
let message: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
title = this.i18n.t('app.NOTIFICATION.PARENT_INTERNAL_TRANSFER_TITLE', { lang: locale });
|
||||||
|
message = this.i18n.t('app.NOTIFICATION.PARENT_INTERNAL_TRANSFER_MESSAGE', {
|
||||||
|
lang: locale,
|
||||||
|
args: {
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency,
|
||||||
|
childName: childName,
|
||||||
|
balance: formattedBalance,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (i18nError: any) {
|
||||||
|
console.error(`[TransactionNotificationListener] i18n error in parent internal transfer:`, i18nError);
|
||||||
|
this.logger.error(`i18n translation failed: ${i18nError?.message}`, i18nError?.stack);
|
||||||
|
title = 'Internal Transfer Completed';
|
||||||
|
message = `${formattedAmount} ${currency} has been transferred to ${childName}'s card. ${childName}'s balance is ${formattedBalance} ${currency}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.notificationFactory.send({
|
||||||
|
userId: parentUser.id,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
scope: NotificationScope.PARENT_INTERNAL_TRANSFER,
|
||||||
|
preferences: this.getUserPreferences(parentUser),
|
||||||
|
data: {
|
||||||
|
transactionId: transaction.id,
|
||||||
|
childId: childUser.id,
|
||||||
|
childName: childName,
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency: currency, // ISO currency code (SAR, USD, etc.)
|
||||||
|
balance: formattedBalance,
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -3,19 +3,30 @@ import { forwardRef, Module } from '@nestjs/common';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { TwilioModule } from 'nestjs-twilio';
|
import { TwilioModule } from 'nestjs-twilio';
|
||||||
|
import { CardModule } from '~/card/card.module';
|
||||||
import { RedisModule } from '~/common/redis/redis.module';
|
import { RedisModule } from '~/common/redis/redis.module';
|
||||||
import { buildMailerOptions, buildTwilioOptions } from '~/core/module-options';
|
import { buildMailerOptions, buildTwilioOptions } from '~/core/module-options';
|
||||||
import { UserModule } from '~/user/user.module';
|
import { UserModule } from '~/user/user.module';
|
||||||
import { NotificationsController } from './controllers';
|
import { NotificationsController } from './controllers';
|
||||||
import { Notification } from './entities';
|
import { Notification } from './entities';
|
||||||
import { NotificationCreatedListener } from './listeners';
|
import {
|
||||||
|
CardNotificationListener,
|
||||||
|
KycNotificationListener,
|
||||||
|
MoneyRequestNotificationListener,
|
||||||
|
NotificationCreatedListener,
|
||||||
|
ProfileNotificationListener,
|
||||||
|
SystemAlertNotificationListener,
|
||||||
|
TransactionNotificationListener,
|
||||||
|
} from './listeners';
|
||||||
import { NotificationsRepository } from './repositories';
|
import { NotificationsRepository } from './repositories';
|
||||||
import { FirebaseService, NotificationsService, TwilioService } from './services';
|
import { FirebaseService, NotificationFactory, NotificationsService, TwilioService } from './services';
|
||||||
|
import { MessagingSystemFactory, RedisPubSubMessagingService } from './services/messaging';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
forwardRef(() => RedisModule.register()),
|
forwardRef(() => RedisModule.register()),
|
||||||
forwardRef(() => UserModule),
|
forwardRef(() => UserModule),
|
||||||
|
forwardRef(() => CardModule),
|
||||||
TypeOrmModule.forFeature([Notification]),
|
TypeOrmModule.forFeature([Notification]),
|
||||||
TwilioModule.forRootAsync({
|
TwilioModule.forRootAsync({
|
||||||
useFactory: buildTwilioOptions,
|
useFactory: buildTwilioOptions,
|
||||||
@ -28,12 +39,21 @@ import { FirebaseService, NotificationsService, TwilioService } from './services
|
|||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
NotificationsService,
|
NotificationsService,
|
||||||
|
NotificationFactory,
|
||||||
FirebaseService,
|
FirebaseService,
|
||||||
NotificationsRepository,
|
NotificationsRepository,
|
||||||
TwilioService,
|
TwilioService,
|
||||||
NotificationCreatedListener,
|
NotificationCreatedListener,
|
||||||
|
TransactionNotificationListener,
|
||||||
|
MoneyRequestNotificationListener,
|
||||||
|
KycNotificationListener,
|
||||||
|
CardNotificationListener,
|
||||||
|
ProfileNotificationListener,
|
||||||
|
SystemAlertNotificationListener,
|
||||||
|
RedisPubSubMessagingService,
|
||||||
|
MessagingSystemFactory,
|
||||||
],
|
],
|
||||||
exports: [NotificationsService, NotificationCreatedListener],
|
exports: [NotificationsService, NotificationFactory, NotificationCreatedListener],
|
||||||
controllers: [NotificationsController],
|
controllers: [NotificationsController],
|
||||||
})
|
})
|
||||||
export class NotificationModule {}
|
export class NotificationModule {}
|
||||||
|
|||||||
@ -1,29 +1,77 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import * as admin from 'firebase-admin';
|
import * as admin from 'firebase-admin';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class FirebaseService {
|
export class FirebaseService {
|
||||||
private readonly logger = new Logger(FirebaseService.name);
|
private readonly logger = new Logger(FirebaseService.name);
|
||||||
|
|
||||||
constructor(private readonly configService: ConfigService) {
|
constructor(private readonly configService: ConfigService) {
|
||||||
admin.initializeApp({
|
try {
|
||||||
credential: admin.credential.cert({
|
this.logger.log('🔥 Initializing Firebase Admin SDK...');
|
||||||
projectId: this.configService.get('FIREBASE_PROJECT_ID'),
|
|
||||||
clientEmail: this.configService.get('FIREBASE_CLIENT_EMAIL'),
|
const projectId = this.configService.get('FIREBASE_PROJECT_ID');
|
||||||
privateKey: this.configService.get('FIREBASE_PRIVATE_KEY').replace(/\\n/g, '\n'),
|
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,
|
||||||
|
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) {
|
async sendNotification(tokens: string | string[], title: string, body: string, data?: Record<string, string>) {
|
||||||
this.logger.log(`Sending push notification to ${tokens}`);
|
this.logger.log(
|
||||||
const message = {
|
`Sending push notification to ${Array.isArray(tokens) ? tokens.length : 1} device(s)`,
|
||||||
notification: {
|
);
|
||||||
title,
|
|
||||||
body,
|
|
||||||
},
|
|
||||||
tokens: Array.isArray(tokens) ? tokens : [tokens],
|
|
||||||
};
|
|
||||||
|
|
||||||
admin.messaging().sendEachForMulticast(message);
|
try {
|
||||||
|
const message = {
|
||||||
|
notification: {
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
},
|
||||||
|
data: data || {},
|
||||||
|
tokens: Array.isArray(tokens) ? tokens : [tokens],
|
||||||
|
};
|
||||||
|
|
||||||
|
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 './firebase.service';
|
||||||
|
export * from './notification-factory.service';
|
||||||
export * from './notifications.service';
|
export * from './notifications.service';
|
||||||
export * from './twilio.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,150 @@
|
|||||||
|
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
|
||||||
|
*
|
||||||
|
* Note: Notifications are always saved to the database (via PUSH channel)
|
||||||
|
* for history/audit purposes, even if push notifications are disabled.
|
||||||
|
* The preferences only control whether push/email/SMS are actually sent.
|
||||||
|
*
|
||||||
|
* @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>[] = [];
|
||||||
|
|
||||||
|
// Always create notification record in database (via PUSH channel for storage)
|
||||||
|
// This ensures notifications are saved for history, even if push is disabled
|
||||||
|
this.logger.debug(`Creating notification record for user ${payload.userId}`);
|
||||||
|
promises.push(
|
||||||
|
this.sendToChannel(payload, NotificationChannel.PUSH)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Only send via additional channels if enabled
|
||||||
|
// Note: PUSH channel is already added above for database storage
|
||||||
|
// The actual push delivery will check preferences in FirebaseService
|
||||||
|
|
||||||
|
await Promise.all(promises);
|
||||||
|
|
||||||
|
const activeChannels = preferences.isPushEnabled ? 1 : 0;
|
||||||
|
this.logger.log(
|
||||||
|
`Notification sent to user ${payload.userId} via ${activeChannels} active channel(s) ` +
|
||||||
|
`(saved to database regardless of preferences)`
|
||||||
|
);
|
||||||
|
} 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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -6,8 +6,9 @@ import { OtpType } from '../../otp/enums';
|
|||||||
import { ISendOtp } from '../../otp/interfaces';
|
import { ISendOtp } from '../../otp/interfaces';
|
||||||
import { SendEmailRequestDto } from '../dtos/request';
|
import { SendEmailRequestDto } from '../dtos/request';
|
||||||
import { Notification } from '../entities';
|
import { Notification } from '../entities';
|
||||||
import { EventType, NotificationChannel, NotificationScope } from '../enums';
|
import { EventType, NotificationChannel, NotificationScope, NotificationStatus } from '../enums';
|
||||||
import { NotificationsRepository } from '../repositories';
|
import { NotificationsRepository } from '../repositories';
|
||||||
|
import { MessagingSystemFactory } from './messaging/messaging-system-factory.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class NotificationsService {
|
export class NotificationsService {
|
||||||
@ -17,6 +18,7 @@ export class NotificationsService {
|
|||||||
|
|
||||||
@Inject(forwardRef(() => RedisPubSubService))
|
@Inject(forwardRef(() => RedisPubSubService))
|
||||||
private readonly redisPubSubService: RedisPubSubService,
|
private readonly redisPubSubService: RedisPubSubService,
|
||||||
|
private readonly messagingSystemFactory: MessagingSystemFactory,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async getNotifications(userId: string, pageOptionsDto: PageOptionsRequestDto) {
|
async getNotifications(userId: string, pageOptionsDto: PageOptionsRequestDto) {
|
||||||
@ -31,9 +33,32 @@ export class NotificationsService {
|
|||||||
return { notifications, count, unreadCount };
|
return { notifications, count, unreadCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
createNotification(notification: Partial<Notification>) {
|
async createNotification(notification: Partial<Notification>) {
|
||||||
this.logger.log(`Creating notification for user ${notification.userId}`);
|
this.logger.log(`Creating notification for user ${notification.userId}`);
|
||||||
return this.notificationRepository.createNotification(notification);
|
const savedNotification = await this.notificationRepository.createNotification({
|
||||||
|
...notification,
|
||||||
|
status: notification.status || NotificationStatus.UNREAD,
|
||||||
|
});
|
||||||
|
|
||||||
|
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) {
|
markAsRead(userId: string) {
|
||||||
@ -42,34 +67,25 @@ export class NotificationsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async sendEmailAsync(data: SendEmailRequestDto) {
|
async sendEmailAsync(data: SendEmailRequestDto) {
|
||||||
this.logger.log(`emitting ${EventType.NOTIFICATION_CREATED} event`);
|
this.logger.log(`Creating email notification for ${data.to}`);
|
||||||
const notification = await this.createNotification({
|
await this.createNotification({
|
||||||
recipient: data.to,
|
recipient: data.to,
|
||||||
title: data.subject,
|
title: data.subject,
|
||||||
message: '',
|
message: '',
|
||||||
scope: NotificationScope.USER_INVITED,
|
scope: NotificationScope.USER_INVITED,
|
||||||
channel: NotificationChannel.EMAIL,
|
channel: NotificationChannel.EMAIL,
|
||||||
});
|
data: data.data,
|
||||||
// return this.redisPubSubService.emit(EventType.NOTIFICATION_CREATED, notification, data.data);
|
|
||||||
this.redisPubSubService.publishEvent(EventType.NOTIFICATION_CREATED, {
|
|
||||||
...notification,
|
|
||||||
data,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendOtpNotification(sendOtpRequest: ISendOtp, otp: string) {
|
async sendOtpNotification(sendOtpRequest: ISendOtp, otp: string) {
|
||||||
this.logger.log(`Sending OTP to ${sendOtpRequest.recipient}`);
|
this.logger.log(`Sending OTP to ${sendOtpRequest.recipient}`);
|
||||||
const notification = await this.createNotification({
|
return this.createNotification({
|
||||||
recipient: sendOtpRequest.recipient,
|
recipient: sendOtpRequest.recipient,
|
||||||
title: OTP_TITLE,
|
title: OTP_TITLE,
|
||||||
message: OTP_BODY.replace('{otp}', otp),
|
message: OTP_BODY.replace('{otp}', otp),
|
||||||
scope: NotificationScope.OTP,
|
scope: NotificationScope.OTP,
|
||||||
channel: sendOtpRequest.otpType === OtpType.EMAIL ? NotificationChannel.EMAIL : NotificationChannel.SMS,
|
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 },
|
data: { otp },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -14,7 +14,15 @@ export class RedisModule {
|
|||||||
{
|
{
|
||||||
provide: 'REDIS_PUBLISHER',
|
provide: 'REDIS_PUBLISHER',
|
||||||
useFactory: async (configService: ConfigService) => {
|
useFactory: async (configService: ConfigService) => {
|
||||||
const publisher = createClient({ url: configService.get<string>('REDIS_URL') });
|
// Skip Redis connection during migration generation
|
||||||
|
if (process.env.MIGRATIONS_RUN === 'false') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const redisUrl = configService.get<string>('REDIS_URL');
|
||||||
|
if (!redisUrl) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const publisher = createClient({ url: redisUrl });
|
||||||
await publisher.connect();
|
await publisher.connect();
|
||||||
return publisher;
|
return publisher;
|
||||||
},
|
},
|
||||||
@ -24,7 +32,15 @@ export class RedisModule {
|
|||||||
{
|
{
|
||||||
provide: 'REDIS_SUBSCRIBER',
|
provide: 'REDIS_SUBSCRIBER',
|
||||||
useFactory: async (configService: ConfigService) => {
|
useFactory: async (configService: ConfigService) => {
|
||||||
const subscriber = createClient({ url: configService.get<string>('REDIS_URL') });
|
// Skip Redis connection during migration generation
|
||||||
|
if (process.env.MIGRATIONS_RUN === 'false') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const redisUrl = configService.get<string>('REDIS_URL');
|
||||||
|
if (!redisUrl) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const subscriber = createClient({ url: redisUrl });
|
||||||
await subscriber.connect();
|
await subscriber.connect();
|
||||||
return subscriber;
|
return subscriber;
|
||||||
},
|
},
|
||||||
@ -32,7 +48,11 @@ export class RedisModule {
|
|||||||
},
|
},
|
||||||
RedisPubSubService,
|
RedisPubSubService,
|
||||||
],
|
],
|
||||||
exports: [RedisPubSubService],
|
exports: [
|
||||||
|
RedisPubSubService,
|
||||||
|
'REDIS_PUBLISHER',
|
||||||
|
'REDIS_SUBSCRIBER',
|
||||||
|
],
|
||||||
imports: [NotificationModule],
|
imports: [NotificationModule],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -15,6 +15,10 @@ export class RedisPubSubService implements OnModuleInit {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
onModuleInit() {
|
onModuleInit() {
|
||||||
|
// Skip subscription during migration generation
|
||||||
|
if (process.env.MIGRATIONS_RUN === 'false' || !this.subscriber) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.subscriber.subscribe(EventType.NOTIFICATION_CREATED, async (message) => {
|
this.subscriber.subscribe(EventType.NOTIFICATION_CREATED, async (message) => {
|
||||||
const data = JSON.parse(message);
|
const data = JSON.parse(message);
|
||||||
this.logger.log('Received message on NOTIFICATION_CREATED channel:', data);
|
this.logger.log('Received message on NOTIFICATION_CREATED channel:', data);
|
||||||
|
|||||||
111
src/common/utils/currency.util.ts
Normal file
111
src/common/utils/currency.util.ts
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
/**
|
||||||
|
* Currency utility functions
|
||||||
|
* Handles currency code mapping and formatting
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ISO 4217 numeric currency codes to ISO currency code mapping
|
||||||
|
* Common codes used in the system:
|
||||||
|
* - 682: SAR (Saudi Riyal)
|
||||||
|
* - 900: USD (US Dollar) - if used
|
||||||
|
* - 784: AED (UAE Dirham)
|
||||||
|
* - 414: KWD (Kuwaiti Dinar)
|
||||||
|
* - 512: OMR (Omani Rial)
|
||||||
|
* - 048: BHD (Bahraini Dinar)
|
||||||
|
* - 400: JOD (Jordanian Dinar)
|
||||||
|
*/
|
||||||
|
export const NUMERIC_TO_CURRENCY_CODE: Record<string, string> = {
|
||||||
|
'682': 'SAR',
|
||||||
|
'900': 'USD',
|
||||||
|
'784': 'AED',
|
||||||
|
'414': 'KWD',
|
||||||
|
'512': 'OMR',
|
||||||
|
'048': 'BHD',
|
||||||
|
'400': 'JOD',
|
||||||
|
'586': 'PKR',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Currency decimal places mapping
|
||||||
|
* ISO 4217 standard decimal places for each currency
|
||||||
|
*/
|
||||||
|
export const CURRENCY_DECIMAL_PLACES: Record<string, number> = {
|
||||||
|
'SAR': 2, // Saudi Riyal
|
||||||
|
'USD': 2, // US Dollar
|
||||||
|
'AED': 2, // UAE Dirham
|
||||||
|
'KWD': 3, // Kuwaiti Dinar
|
||||||
|
'OMR': 3, // Omani Rial
|
||||||
|
'BHD': 3, // Bahraini Dinar
|
||||||
|
'JOD': 3, // Jordanian Dinar
|
||||||
|
'PKR': 2, // Pakistani Rupee
|
||||||
|
'JPY': 0, // Japanese Yen (if used)
|
||||||
|
'KRW': 0, // South Korean Won (if used)
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert numeric currency code to ISO currency code
|
||||||
|
* @param numericCode - Numeric currency code (e.g., '682')
|
||||||
|
* @returns ISO currency code (e.g., 'SAR') or the original code if not found
|
||||||
|
*/
|
||||||
|
export function numericToCurrencyCode(numericCode: string | null | undefined): string {
|
||||||
|
if (!numericCode) {
|
||||||
|
return 'SAR'; // Default fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
// If already an ISO code (3 letters), return as is
|
||||||
|
if (/^[A-Z]{3}$/.test(numericCode)) {
|
||||||
|
return numericCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map numeric code to ISO code
|
||||||
|
return NUMERIC_TO_CURRENCY_CODE[numericCode] || numericCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format amount based on currency decimal places
|
||||||
|
* @param amount - Amount to format (number or string)
|
||||||
|
* @param currency - ISO currency code (e.g., 'SAR', 'KWD')
|
||||||
|
* @returns Formatted amount string
|
||||||
|
*/
|
||||||
|
export function formatCurrencyAmount(amount: number | string, currency: string): string {
|
||||||
|
const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
|
||||||
|
|
||||||
|
if (isNaN(numAmount)) {
|
||||||
|
return '0';
|
||||||
|
}
|
||||||
|
|
||||||
|
const decimalPlaces = CURRENCY_DECIMAL_PLACES[currency] ?? 2;
|
||||||
|
return numAmount.toFixed(decimalPlaces);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get currency from account or transaction, with fallback
|
||||||
|
* @param accountCurrency - Currency from account entity (may be numeric like '682')
|
||||||
|
* @param transactionCurrency - Currency from transaction entity (may be numeric)
|
||||||
|
* @param fallback - Fallback currency (default: 'SAR')
|
||||||
|
* @returns ISO currency code
|
||||||
|
*/
|
||||||
|
export function getCurrency(
|
||||||
|
accountCurrency?: string | null,
|
||||||
|
transactionCurrency?: string | null,
|
||||||
|
fallback: string = 'SAR'
|
||||||
|
): string {
|
||||||
|
// Convert account currency first (it may be numeric like '682')
|
||||||
|
if (accountCurrency) {
|
||||||
|
const converted = numericToCurrencyCode(accountCurrency);
|
||||||
|
if (converted && converted !== accountCurrency) {
|
||||||
|
return converted; // Successfully converted from numeric to ISO
|
||||||
|
}
|
||||||
|
// If already ISO format, return as is
|
||||||
|
if (/^[A-Z]{3}$/.test(accountCurrency)) {
|
||||||
|
return accountCurrency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert transaction currency (may be numeric)
|
||||||
|
if (transactionCurrency) {
|
||||||
|
return numericToCurrencyCode(transactionCurrency);
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
@ -1,12 +1,12 @@
|
|||||||
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
import { IJwtPayload } from '~/auth/interfaces';
|
||||||
import { AuthenticatedUser } from '~/common/decorators';
|
import { AuthenticatedUser } from '~/common/decorators';
|
||||||
import { AccessTokenGuard } from '~/common/guards';
|
import { AccessTokenGuard } from '~/common/guards';
|
||||||
import { ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
|
import { ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
|
||||||
import { ResponseFactory } from '~/core/utils';
|
import { ResponseFactory } from '~/core/utils';
|
||||||
import { InitiateKycRequestDto } from '../dtos/request';
|
import { InitiateKycRequestDto } from '../dtos/request';
|
||||||
import { CustomerResponseDto, InitiateKycResponseDto } from '../dtos/response';
|
import { CustomerResponseDto, InitiateKycResponseDto, KycMetadataResponseDto } from '../dtos/response';
|
||||||
import { CustomerService } from '../services';
|
import { CustomerService } from '../services';
|
||||||
|
|
||||||
@Controller('customers')
|
@Controller('customers')
|
||||||
@ -30,6 +30,16 @@ export class CustomerController {
|
|||||||
async initiateKyc(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: InitiateKycRequestDto) {
|
async initiateKyc(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: InitiateKycRequestDto) {
|
||||||
const res = await this.customerService.initiateKycRequest(sub, body);
|
const res = await this.customerService.initiateKycRequest(sub, body);
|
||||||
|
|
||||||
return ResponseFactory.data(new InitiateKycResponseDto(res.randomNumber));
|
return ResponseFactory.data(new InitiateKycResponseDto(res));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/kyc/onboard-metadata')
|
||||||
|
@UseGuards(AccessTokenGuard)
|
||||||
|
@ApiOperation({ summary: 'Get KYC onboarding form metadata' })
|
||||||
|
@ApiDataResponse(KycMetadataResponseDto)
|
||||||
|
async getKycMetadata() {
|
||||||
|
const metadata = await this.customerService.getKycOnboardMetadata();
|
||||||
|
|
||||||
|
return ResponseFactory.data(metadata);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,14 +4,14 @@ import { NeoLeapModule } from '~/common/modules/neoleap/neoleap.module';
|
|||||||
import { GuardianModule } from '~/guardian/guardian.module';
|
import { GuardianModule } from '~/guardian/guardian.module';
|
||||||
import { UserModule } from '~/user/user.module';
|
import { UserModule } from '~/user/user.module';
|
||||||
import { CustomerController } from './controllers';
|
import { CustomerController } from './controllers';
|
||||||
import { Customer } from './entities';
|
import { Customer, KycTransaction } from './entities';
|
||||||
import { CustomerRepository } from './repositories/customer.repository';
|
import { CustomerRepository, KycTransactionRepository } from './repositories';
|
||||||
import { CustomerService } from './services';
|
import { CustomerService, MetadataService } from './services';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Customer]), GuardianModule, forwardRef(() => UserModule), NeoLeapModule],
|
imports: [TypeOrmModule.forFeature([Customer, KycTransaction]), GuardianModule, forwardRef(() => UserModule), NeoLeapModule],
|
||||||
controllers: [CustomerController],
|
controllers: [CustomerController],
|
||||||
providers: [CustomerService, CustomerRepository],
|
providers: [CustomerService, CustomerRepository, KycTransactionRepository, MetadataService],
|
||||||
exports: [CustomerService],
|
exports: [CustomerService],
|
||||||
})
|
})
|
||||||
export class CustomerModule {}
|
export class CustomerModule {}
|
||||||
|
|||||||
@ -1,8 +1,55 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsDateString, IsEmail, IsEnum, IsOptional, IsString, Matches } from 'class-validator';
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
import { isValidSaudiId } from '~/core/decorators/validations';
|
import { Gender, IncomeRange, IncomeSource, JobCategory, JobSector, PoiType } from '~/customer/enums';
|
||||||
|
|
||||||
export class InitiateKycRequestDto {
|
export class InitiateKycRequestDto {
|
||||||
@ApiProperty({ example: '999300024' })
|
@ApiProperty({ example: '2586234623', description: 'Saudi National ID or Iqama number' })
|
||||||
@isValidSaudiId({ message: i18n('validation.isValidSaudiId', { path: 'general', property: 'customer.nationalId' }) })
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.poiNumber' }) })
|
||||||
nationalId!: string;
|
poiNumber!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: PoiType, example: PoiType.NAT, default: PoiType.NAT })
|
||||||
|
@IsEnum(PoiType, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.poiType' }) })
|
||||||
|
poiType!: PoiType;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '0512345678', pattern: '^05\\d{8}$' })
|
||||||
|
@Matches(/^05\d{8}$/, { message: i18n('validation.Matches', { path: 'general', property: 'customer.mobileNumber' }) })
|
||||||
|
mobileNumber!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'user@zodwallet.com', required: false })
|
||||||
|
@IsEmail({}, { message: i18n('validation.IsEmail', { path: 'general', property: 'customer.email' }) })
|
||||||
|
@IsOptional()
|
||||||
|
email?: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '1990-01-01', format: 'date' })
|
||||||
|
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.dateOfBirth' }) })
|
||||||
|
dateOfBirth!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2030-12-31', format: 'date', description: 'National ID expiry date' })
|
||||||
|
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.nationalIdExpiry' }) })
|
||||||
|
nationalIdExpiry!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: Gender, example: Gender.MALE })
|
||||||
|
@IsEnum(Gender, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.gender' }) })
|
||||||
|
gender!: Gender;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: JobSector, example: JobSector.PRIVATE_SECTOR })
|
||||||
|
@IsEnum(JobSector, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.jobSector' }) })
|
||||||
|
jobSector!: JobSector;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Test Company Ltd' })
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.employer' }) })
|
||||||
|
employer!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: IncomeSource, example: IncomeSource.SALARY })
|
||||||
|
@IsEnum(IncomeSource, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.incomeSource' }) })
|
||||||
|
incomeSource!: IncomeSource;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: JobCategory, example: JobCategory.ENGINEER })
|
||||||
|
@IsEnum(JobCategory, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.jobCategory' }) })
|
||||||
|
jobCategory!: JobCategory;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: IncomeRange, example: IncomeRange.RANGE_10000_20000 })
|
||||||
|
@IsEnum(IncomeRange, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.incomeRange' }) })
|
||||||
|
incomeRange!: IncomeRange;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -34,15 +34,6 @@ export class CustomerResponseDto {
|
|||||||
@ApiProperty({ example: 'JO' })
|
@ApiProperty({ example: 'JO' })
|
||||||
countryOfResidence!: string;
|
countryOfResidence!: string;
|
||||||
|
|
||||||
@ApiProperty({ example: 'Employee' })
|
|
||||||
sourceOfIncome!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Software Development' })
|
|
||||||
profession!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Full-time' })
|
|
||||||
professionType!: string;
|
|
||||||
|
|
||||||
@ApiProperty({ example: false })
|
@ApiProperty({ example: false })
|
||||||
isPep!: boolean;
|
isPep!: boolean;
|
||||||
|
|
||||||
@ -58,24 +49,6 @@ export class CustomerResponseDto {
|
|||||||
@ApiProperty({ example: 12345 })
|
@ApiProperty({ example: 12345 })
|
||||||
waitingNumber!: number;
|
waitingNumber!: number;
|
||||||
|
|
||||||
@ApiProperty({ example: 'SA' })
|
|
||||||
country!: string | null;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Riyadh' })
|
|
||||||
region!: string | null;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Riyadh City' })
|
|
||||||
city!: string | null;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'Al-Masif' })
|
|
||||||
neighborhood!: string | null;
|
|
||||||
|
|
||||||
@ApiProperty({ example: 'King Fahd Road' })
|
|
||||||
street!: string | null;
|
|
||||||
|
|
||||||
@ApiProperty({ example: '123' })
|
|
||||||
building!: string | null;
|
|
||||||
|
|
||||||
@ApiPropertyOptional({ type: DocumentMetaResponseDto })
|
@ApiPropertyOptional({ type: DocumentMetaResponseDto })
|
||||||
profilePicture!: DocumentMetaResponseDto | null;
|
profilePicture!: DocumentMetaResponseDto | null;
|
||||||
|
|
||||||
@ -90,19 +63,10 @@ export class CustomerResponseDto {
|
|||||||
this.nationalId = customer.nationalId;
|
this.nationalId = customer.nationalId;
|
||||||
this.nationalIdExpiry = customer.nationalIdExpiry;
|
this.nationalIdExpiry = customer.nationalIdExpiry;
|
||||||
this.countryOfResidence = customer.countryOfResidence;
|
this.countryOfResidence = customer.countryOfResidence;
|
||||||
this.sourceOfIncome = customer.sourceOfIncome;
|
|
||||||
this.profession = customer.profession;
|
|
||||||
this.professionType = customer.professionType;
|
|
||||||
this.isPep = customer.isPep;
|
this.isPep = customer.isPep;
|
||||||
this.gender = customer.gender;
|
this.gender = customer.gender;
|
||||||
this.isJunior = customer.isJunior;
|
this.isJunior = customer.isJunior;
|
||||||
this.isGuardian = customer.isGuardian;
|
this.isGuardian = customer.isGuardian;
|
||||||
this.waitingNumber = customer.applicationNumber;
|
this.waitingNumber = customer.applicationNumber;
|
||||||
this.country = customer.country;
|
|
||||||
this.region = customer.region;
|
|
||||||
this.city = customer.city;
|
|
||||||
this.neighborhood = customer.neighborhood;
|
|
||||||
this.street = customer.street;
|
|
||||||
this.building = customer.building;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,2 +1,3 @@
|
|||||||
export * from './customer.response.dto';
|
export * from './customer.response.dto';
|
||||||
export * from './initiate-kyc.response.dto';
|
export * from './initiate-kyc.response.dto';
|
||||||
|
export * from './kyc-metadata.response.dto';
|
||||||
|
|||||||
@ -1,10 +1,28 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Expose } from 'class-transformer';
|
||||||
|
|
||||||
export class InitiateKycResponseDto {
|
export class InitiateKycResponseDto {
|
||||||
@ApiProperty()
|
@ApiProperty({ description: 'Internal transaction ID to track this KYC attempt' })
|
||||||
randomNumber!: string;
|
@Expose()
|
||||||
|
transactionId!: string;
|
||||||
|
|
||||||
constructor(randomNumber: string) {
|
@ApiProperty({ description: 'Neoleap state ID for tracking' })
|
||||||
this.randomNumber = randomNumber;
|
@Expose()
|
||||||
|
stateId!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Nafath random code to show to the user', example: '38' })
|
||||||
|
@Expose()
|
||||||
|
nafathRandomCode!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Current status', example: 'IN_PROGRESS' })
|
||||||
|
@Expose()
|
||||||
|
status!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'External customer ID from Neoleap' })
|
||||||
|
@Expose()
|
||||||
|
externalCustomerId!: string;
|
||||||
|
|
||||||
|
constructor(data: Partial<InitiateKycResponseDto>) {
|
||||||
|
Object.assign(this, data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
12
src/customer/dtos/response/kyc-metadata.response.dto.ts
Normal file
12
src/customer/dtos/response/kyc-metadata.response.dto.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
export class MetadataOptionDto {
|
||||||
|
value!: string;
|
||||||
|
label!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class KycMetadataResponseDto {
|
||||||
|
poiTypes!: MetadataOptionDto[];
|
||||||
|
jobSectors!: MetadataOptionDto[];
|
||||||
|
incomeSources!: MetadataOptionDto[];
|
||||||
|
jobCategories!: MetadataOptionDto[];
|
||||||
|
incomeRanges!: MetadataOptionDto[];
|
||||||
|
}
|
||||||
@ -49,15 +49,6 @@ export class Customer extends BaseEntity {
|
|||||||
@Column('varchar', { length: 255, nullable: true, name: 'country_of_residence' })
|
@Column('varchar', { length: 255, nullable: true, name: 'country_of_residence' })
|
||||||
countryOfResidence!: CountryIso;
|
countryOfResidence!: CountryIso;
|
||||||
|
|
||||||
@Column('varchar', { length: 255, nullable: true, name: 'source_of_income' })
|
|
||||||
sourceOfIncome!: string;
|
|
||||||
|
|
||||||
@Column('varchar', { length: 255, nullable: true, name: 'profession' })
|
|
||||||
profession!: string;
|
|
||||||
|
|
||||||
@Column('varchar', { length: 255, nullable: true, name: 'profession_type' })
|
|
||||||
professionType!: string;
|
|
||||||
|
|
||||||
@Column('boolean', { default: false, name: 'is_pep' })
|
@Column('boolean', { default: false, name: 'is_pep' })
|
||||||
isPep!: boolean;
|
isPep!: boolean;
|
||||||
|
|
||||||
@ -77,23 +68,27 @@ export class Customer extends BaseEntity {
|
|||||||
@Column('varchar', { name: 'user_id' })
|
@Column('varchar', { name: 'user_id' })
|
||||||
userId!: string;
|
userId!: string;
|
||||||
|
|
||||||
@Column('varchar', { name: 'country', length: 255, nullable: true })
|
// KYC-specific fields
|
||||||
country!: CountryIso;
|
@Column('varchar', { length: 255, nullable: true, name: 'neoleap_external_customer_id' })
|
||||||
|
neoleapExternalCustomerId!: string | null;
|
||||||
|
|
||||||
@Column('varchar', { name: 'region', length: 255, nullable: true })
|
@Column('varchar', { length: 100, nullable: true, name: 'job_sector' })
|
||||||
region!: string;
|
jobSector!: string | null;
|
||||||
|
|
||||||
@Column('varchar', { name: 'city', length: 255, nullable: true })
|
@Column('varchar', { length: 255, nullable: true, name: 'employer' })
|
||||||
city!: string;
|
employer!: string | null;
|
||||||
|
|
||||||
@Column('varchar', { name: 'neighborhood', length: 255, nullable: true })
|
@Column('varchar', { length: 100, nullable: true, name: 'income_source' })
|
||||||
neighborhood!: string;
|
incomeSource!: string | null;
|
||||||
|
|
||||||
@Column('varchar', { name: 'street', length: 255, nullable: true })
|
@Column('varchar', { length: 100, nullable: true, name: 'job_category' })
|
||||||
street!: string;
|
jobCategory!: string | null;
|
||||||
|
|
||||||
@Column('varchar', { name: 'building', length: 255, nullable: true })
|
@Column('varchar', { length: 100, nullable: true, name: 'income_range' })
|
||||||
building!: string;
|
incomeRange!: string | null;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 20, nullable: true, name: 'mobile_number' })
|
||||||
|
mobileNumber!: string | null;
|
||||||
|
|
||||||
@OneToOne(() => User, (user) => user.customer, { onDelete: 'CASCADE' })
|
@OneToOne(() => User, (user) => user.customer, { onDelete: 'CASCADE' })
|
||||||
@JoinColumn({ name: 'user_id' })
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
|||||||
@ -1 +1,2 @@
|
|||||||
export * from './customer.entity';
|
export * from './customer.entity';
|
||||||
|
export * from './kyc-transaction.entity';
|
||||||
|
|||||||
76
src/customer/entities/kyc-transaction.entity.ts
Normal file
76
src/customer/entities/kyc-transaction.entity.ts
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
import {
|
||||||
|
BaseEntity,
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { Customer } from './customer.entity';
|
||||||
|
import { User } from '~/user/entities';
|
||||||
|
|
||||||
|
@Entity('kyc_transactions')
|
||||||
|
export class KycTransaction extends BaseEntity {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@Column('uuid', { name: 'customer_id' })
|
||||||
|
customerId!: string;
|
||||||
|
|
||||||
|
@Column('uuid', { name: 'user_id' })
|
||||||
|
userId!: string;
|
||||||
|
|
||||||
|
// National ID from form
|
||||||
|
@Column('varchar', { length: 50, name: 'national_id', nullable: false })
|
||||||
|
nationalId!: string;
|
||||||
|
|
||||||
|
// Neoleap IDs
|
||||||
|
@Column('varchar', { length: 255, unique: true, name: 'state_id' })
|
||||||
|
stateId!: string;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, nullable: true, name: 'external_customer_id' })
|
||||||
|
externalCustomerId!: string | null;
|
||||||
|
|
||||||
|
// Nafath details
|
||||||
|
@Column('varchar', { length: 10, nullable: true, name: 'nafath_random_code' })
|
||||||
|
nafathRandomCode!: string | null;
|
||||||
|
|
||||||
|
// Status tracking
|
||||||
|
@Column('varchar', { length: 50, default: 'INITIATED', name: 'status' })
|
||||||
|
status!: string;
|
||||||
|
|
||||||
|
// Audit trail
|
||||||
|
@Column('jsonb', { name: 'form_data' })
|
||||||
|
formData!: any;
|
||||||
|
|
||||||
|
@Column('varchar', { length: 255, nullable: true, name: 'callback_id' })
|
||||||
|
callbackId!: string | null;
|
||||||
|
|
||||||
|
// Timestamps
|
||||||
|
@Column('timestamp', { default: () => 'CURRENT_TIMESTAMP', name: 'initiated_at' })
|
||||||
|
initiatedAt!: Date;
|
||||||
|
|
||||||
|
@Column('timestamp', { nullable: true, name: 'completed_at' })
|
||||||
|
completedAt!: Date | null;
|
||||||
|
|
||||||
|
@Column('timestamp', { nullable: true, name: 'expires_at' })
|
||||||
|
expiresAt!: Date | null;
|
||||||
|
|
||||||
|
@CreateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'created_at' })
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'updated_at' })
|
||||||
|
updatedAt!: Date;
|
||||||
|
|
||||||
|
// Relationships
|
||||||
|
@ManyToOne(() => Customer, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'customer_id' })
|
||||||
|
customer!: Customer;
|
||||||
|
|
||||||
|
@ManyToOne(() => User, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
user!: User;
|
||||||
|
}
|
||||||
|
|
||||||
8
src/customer/enums/income-range.enum.ts
Normal file
8
src/customer/enums/income-range.enum.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
export enum IncomeRange {
|
||||||
|
BELOW_2000 = 'SAR 2,000 and below',
|
||||||
|
RANGE_2000_5000 = 'SAR 2,000 to 5,000',
|
||||||
|
RANGE_5000_10000 = 'SAR 5,000 to 10,000',
|
||||||
|
RANGE_10000_20000 = 'SAR 10,000 to 20,000',
|
||||||
|
ABOVE_20000 = 'SAR 20,000 and above',
|
||||||
|
}
|
||||||
|
|
||||||
9
src/customer/enums/income-source.enum.ts
Normal file
9
src/customer/enums/income-source.enum.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
export enum IncomeSource {
|
||||||
|
SALARY = 'SALARY',
|
||||||
|
ANCESTRAL = 'ANCESTRAL',
|
||||||
|
REAL_ESTATE = 'REAL_ESTATE',
|
||||||
|
INVESTMENT_RETURNS = 'INVESTMENT_RETURNS',
|
||||||
|
RENTAL_INCOME = 'RENTAL_INCOME',
|
||||||
|
OTHER = 'OTHER',
|
||||||
|
}
|
||||||
|
|
||||||
@ -1,3 +1,8 @@
|
|||||||
export * from './customer-status.enum';
|
export * from './customer-status.enum';
|
||||||
export * from './gender.enum';
|
export * from './gender.enum';
|
||||||
export * from './kyc-status.enum';
|
export * from './kyc-status.enum';
|
||||||
|
export * from './poi-type.enum';
|
||||||
|
export * from './job-sector.enum';
|
||||||
|
export * from './income-source.enum';
|
||||||
|
export * from './job-category.enum';
|
||||||
|
export * from './income-range.enum';
|
||||||
|
|||||||
57
src/customer/enums/job-category.enum.ts
Normal file
57
src/customer/enums/job-category.enum.ts
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
export enum JobCategory {
|
||||||
|
ASSISTANT_MINISTER = 'ASSISTANT_MINISTER',
|
||||||
|
DEPUTY_MINISTER = 'DEPUTY_MINISTER',
|
||||||
|
UNDER_SECRETARY = 'UNDER_SECRETARY',
|
||||||
|
GENERAL_MANAGER = 'GENERAL_MANAGER',
|
||||||
|
CHAIRMAN = 'CHAIRMAN',
|
||||||
|
MANAGER = 'MANAGER',
|
||||||
|
PROFESSOR = 'PROFESSOR',
|
||||||
|
HEAD_OF_COURT = 'HEAD_OF_COURT',
|
||||||
|
JUDGE = 'JUDGE',
|
||||||
|
LAWYER = 'LAWYER',
|
||||||
|
SCIENTIST = 'SCIENTIST',
|
||||||
|
NOTARY = 'NOTARY',
|
||||||
|
BUSINESSMAN = 'BUSINESSMAN',
|
||||||
|
MERCHANT = 'MERCHANT',
|
||||||
|
PHARMACIST = 'PHARMACIST',
|
||||||
|
DOCTOR = 'DOCTOR',
|
||||||
|
MEDICAL_TECHNICIAN = 'MEDICAL_TECHNICIAN',
|
||||||
|
NURSE = 'NURSE',
|
||||||
|
ENGINEER = 'ENGINEER',
|
||||||
|
CHEMIST = 'CHEMIST',
|
||||||
|
CONTRACTOR = 'CONTRACTOR',
|
||||||
|
AUDITOR_ACCOUNTANT = 'AUDITOR_ACCOUNTANT',
|
||||||
|
RESEARCHER = 'RESEARCHER',
|
||||||
|
ACCOUNTANT = 'ACCOUNTANT',
|
||||||
|
JOURNALIST = 'JOURNALIST',
|
||||||
|
DESIGNER = 'DESIGNER',
|
||||||
|
COMPUTER_SPECIALIST = 'COMPUTER_SPECIALIST',
|
||||||
|
TRANSLATOR = 'TRANSLATOR',
|
||||||
|
TEACHER = 'TEACHER',
|
||||||
|
PILOT = 'PILOT',
|
||||||
|
HOST = 'HOST',
|
||||||
|
OFFICER = 'OFFICER',
|
||||||
|
SOLDIER = 'SOLDIER',
|
||||||
|
RETIRED = 'RETIRED',
|
||||||
|
SALESMAN = 'SALESMAN',
|
||||||
|
AUTHOR = 'AUTHOR',
|
||||||
|
CRAFTSMAN = 'CRAFTSMAN',
|
||||||
|
SECURITY = 'SECURITY',
|
||||||
|
LABORER = 'LABORER',
|
||||||
|
DRIVER = 'DRIVER',
|
||||||
|
FARMER = 'FARMER',
|
||||||
|
HOUSEWIFE = 'HOUSEWIFE',
|
||||||
|
DIPLOMAT = 'DIPLOMAT',
|
||||||
|
STUDENT = 'STUDENT',
|
||||||
|
FREELANCER = 'FREELANCER',
|
||||||
|
SHEPHERD = 'SHEPHERD',
|
||||||
|
HOUSEMAID_OR_BABYSITTER = 'HOUSEMAID_OR_BABYSITTER',
|
||||||
|
CAPTAIN = 'CAPTAIN',
|
||||||
|
AMBASSADOR = 'AMBASSADOR',
|
||||||
|
MARKETING = 'MARKETING',
|
||||||
|
CONSULTING = 'CONSULTING',
|
||||||
|
SUPERVISOR = 'SUPERVISOR',
|
||||||
|
BANKER = 'BANKER',
|
||||||
|
BODYGUARD_OR_PERSONAL_ASSISTANT = 'BODYGUARD_OR_PERSONAL_ASSISTANT',
|
||||||
|
}
|
||||||
|
|
||||||
12
src/customer/enums/job-sector.enum.ts
Normal file
12
src/customer/enums/job-sector.enum.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
export enum JobSector {
|
||||||
|
GOVERNMENT_SECTOR = 'GOVERNMENT_SECTOR',
|
||||||
|
HOME_MAKER = 'HOME_MAKER',
|
||||||
|
MILITARY = 'MILITARY',
|
||||||
|
PRIVATE_SECTOR = 'PRIVATE_SECTOR',
|
||||||
|
RETIRED = 'RETIRED',
|
||||||
|
SELF_EMPLOYED = 'SELF_EMPLOYED',
|
||||||
|
STUDENT = 'STUDENT',
|
||||||
|
HOUSEHOLD_LABOR = 'HOUSEHOLD_LABOR',
|
||||||
|
UNEMPLOYED = 'UNEMPLOYED',
|
||||||
|
}
|
||||||
|
|
||||||
5
src/customer/enums/poi-type.enum.ts
Normal file
5
src/customer/enums/poi-type.enum.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export enum PoiType {
|
||||||
|
IQA = 'IQA', // Iqama (Resident ID)
|
||||||
|
NAT = 'NAT', // National ID
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,3 @@
|
|||||||
|
export * from './customer.repository';
|
||||||
|
export * from './kyc-transaction.repository';
|
||||||
|
|
||||||
|
|||||||
46
src/customer/repositories/kyc-transaction.repository.ts
Normal file
46
src/customer/repositories/kyc-transaction.repository.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { KycTransaction } from '../entities';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class KycTransactionRepository {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(KycTransaction)
|
||||||
|
private readonly kycTransactionRepository: Repository<KycTransaction>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async create(data: Partial<KycTransaction>): Promise<KycTransaction> {
|
||||||
|
const transaction = this.kycTransactionRepository.create(data);
|
||||||
|
return this.kycTransactionRepository.save(transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByStateId(stateId: string): Promise<KycTransaction | null> {
|
||||||
|
return this.kycTransactionRepository.findOne({
|
||||||
|
where: { stateId },
|
||||||
|
relations: ['customer', 'user'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async findActiveByNationalId(nationalId: string): Promise<KycTransaction | null> {
|
||||||
|
return this.kycTransactionRepository.findOne({
|
||||||
|
where: {
|
||||||
|
nationalId,
|
||||||
|
status: 'IN_PROGRESS',
|
||||||
|
},
|
||||||
|
order: { initiatedAt: 'DESC' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateByStateId(stateId: string, data: Partial<KycTransaction>): Promise<void> {
|
||||||
|
await this.kycTransactionRepository.update({ stateId }, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllByCustomerId(customerId: string): Promise<KycTransaction[]> {
|
||||||
|
return this.kycTransactionRepository.find({
|
||||||
|
where: { customerId },
|
||||||
|
order: { initiatedAt: 'DESC' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -1,25 +1,35 @@
|
|||||||
import { BadRequestException, forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
|
import { BadRequestException, ConflictException, forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||||
import moment from 'moment';
|
import moment from 'moment';
|
||||||
import { Transactional } from 'typeorm-transactional';
|
import { Transactional } from 'typeorm-transactional';
|
||||||
import { CountryIso } from '~/common/enums';
|
import { CountryIso } from '~/common/enums';
|
||||||
import { NumericToCountryIso } from '~/common/mappers';
|
import { NumericToCountryIso } from '~/common/mappers';
|
||||||
import { KycWebhookRequest } from '~/common/modules/neoleap/dtos/requests';
|
import { KycWebhookRequest } from '~/common/modules/neoleap/dtos/requests';
|
||||||
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
||||||
|
import { NOTIFICATION_EVENTS } from '~/common/modules/notification/constants/event-names.constant';
|
||||||
|
import {
|
||||||
|
IKycApprovedEvent,
|
||||||
|
IKycRejectedEvent,
|
||||||
|
} from '~/common/modules/notification/interfaces/notification-events.interface';
|
||||||
import { GuardianService } from '~/guardian/services';
|
import { GuardianService } from '~/guardian/services';
|
||||||
import { CreateJuniorRequestDto } from '~/junior/dtos/request';
|
import { CreateJuniorRequestDto } from '~/junior/dtos/request';
|
||||||
import { User } from '~/user/entities';
|
import { User } from '~/user/entities';
|
||||||
import { InitiateKycRequestDto } from '../dtos/request';
|
import { InitiateKycRequestDto } from '../dtos/request';
|
||||||
import { Customer } from '../entities';
|
import { Customer } from '../entities';
|
||||||
import { Gender, KycStatus } from '../enums';
|
import { Gender, KycStatus } from '../enums';
|
||||||
import { CustomerRepository } from '../repositories/customer.repository';
|
import { CustomerRepository, KycTransactionRepository } from '../repositories';
|
||||||
|
import { MetadataService } from './metadata.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CustomerService {
|
export class CustomerService {
|
||||||
private readonly logger = new Logger(CustomerService.name);
|
private readonly logger = new Logger(CustomerService.name);
|
||||||
constructor(
|
constructor(
|
||||||
private readonly customerRepository: CustomerRepository,
|
private readonly customerRepository: CustomerRepository,
|
||||||
|
private readonly kycTransactionRepo: KycTransactionRepository,
|
||||||
private readonly guardianService: GuardianService,
|
private readonly guardianService: GuardianService,
|
||||||
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
||||||
|
private readonly metadataService: MetadataService,
|
||||||
|
private readonly eventEmitter: EventEmitter2,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async updateCustomer(userId: string, data: Partial<Customer>): Promise<Customer> {
|
async updateCustomer(userId: string, data: Partial<Customer>): Promise<Customer> {
|
||||||
@ -53,23 +63,68 @@ export class CustomerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async initiateKycRequest(customerId: string, body: InitiateKycRequestDto) {
|
async initiateKycRequest(customerId: string, body: InitiateKycRequestDto) {
|
||||||
this.logger.log(`Initiating KYC request for user ${customerId}`);
|
this.logger.log(`Initiating KYC request for customer ${customerId}`);
|
||||||
|
|
||||||
const customer = await this.findCustomerById(customerId);
|
const customer = await this.findCustomerById(customerId);
|
||||||
|
|
||||||
|
// Validate customer is not already verified
|
||||||
if (customer.kycStatus === KycStatus.APPROVED) {
|
if (customer.kycStatus === KycStatus.APPROVED) {
|
||||||
this.logger.error(`KYC for customer ${customerId} is already approved`);
|
this.logger.error(`KYC for customer ${customerId} is already approved`);
|
||||||
throw new BadRequestException('CUSTOMER.KYC_ALREADY_APPROVED');
|
throw new BadRequestException('CUSTOMER.KYC_ALREADY_APPROVED');
|
||||||
}
|
}
|
||||||
|
|
||||||
// I will assume the api for initiating KYC is not allowing me to send customerId as correlationId so I will store the nationalId in the customer entity
|
// Check for active KYC transaction by National ID
|
||||||
|
const activeTransaction = await this.kycTransactionRepo.findActiveByNationalId(body.poiNumber);
|
||||||
|
if (activeTransaction) {
|
||||||
|
this.logger.error(`KYC verification already in progress for National ID ${body.poiNumber}`);
|
||||||
|
throw new ConflictException('KYC verification already in progress for this National ID');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update customer with KYC data
|
||||||
await this.customerRepository.updateCustomer(customerId, {
|
await this.customerRepository.updateCustomer(customerId, {
|
||||||
nationalId: body.nationalId,
|
nationalId: body.poiNumber,
|
||||||
|
dateOfBirth: new Date(body.dateOfBirth),
|
||||||
|
nationalIdExpiry: new Date(body.nationalIdExpiry),
|
||||||
|
gender: body.gender,
|
||||||
|
countryOfResidence: CountryIso.SAUDI_ARABIA, // Always default to Saudi Arabia
|
||||||
|
mobileNumber: body.mobileNumber,
|
||||||
|
jobSector: body.jobSector,
|
||||||
|
employer: body.employer,
|
||||||
|
incomeSource: body.incomeSource,
|
||||||
|
jobCategory: body.jobCategory,
|
||||||
|
incomeRange: body.incomeRange,
|
||||||
kycStatus: KycStatus.PENDING,
|
kycStatus: KycStatus.PENDING,
|
||||||
});
|
});
|
||||||
|
|
||||||
return this.neoleapService.initiateKyc(customerId, body);
|
// Call Neoleap KYC API
|
||||||
|
const neoleapResponse = await this.neoleapService.initiateKycOnboarding(body);
|
||||||
|
|
||||||
|
// Create transaction record
|
||||||
|
const transaction = await this.kycTransactionRepo.create({
|
||||||
|
customerId,
|
||||||
|
userId: customer.userId,
|
||||||
|
nationalId: body.poiNumber,
|
||||||
|
stateId: neoleapResponse.stateId,
|
||||||
|
externalCustomerId: neoleapResponse.externalCustomerId,
|
||||||
|
nafathRandomCode: neoleapResponse.nafathRandomCode,
|
||||||
|
status: neoleapResponse.status,
|
||||||
|
formData: body,
|
||||||
|
initiatedAt: new Date(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update customer with external ID
|
||||||
|
await this.customerRepository.updateCustomer(customerId, {
|
||||||
|
neoleapExternalCustomerId: neoleapResponse.externalCustomerId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return formatted response
|
||||||
|
return {
|
||||||
|
transactionId: transaction.id,
|
||||||
|
stateId: neoleapResponse.stateId,
|
||||||
|
nafathRandomCode: neoleapResponse.nafathRandomCode,
|
||||||
|
status: neoleapResponse.status,
|
||||||
|
externalCustomerId: neoleapResponse.externalCustomerId,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
@ -92,34 +147,59 @@ export class CustomerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async updateCustomerKyc(body: KycWebhookRequest) {
|
async updateCustomerKyc(body: KycWebhookRequest) {
|
||||||
this.logger.log(`Updating KYC for customer with national ID ${body.nationalId}`);
|
this.logger.log(`Updating KYC for stateId ${body.stateId}`);
|
||||||
|
|
||||||
const customer = await this.customerRepository.findOne({ nationalId: body.nationalId });
|
// Find transaction by stateId
|
||||||
|
const transaction = await this.kycTransactionRepo.findByStateId(body.stateId);
|
||||||
if (!customer) {
|
|
||||||
throw new BadRequestException('CUSTOMER.NOT_FOUND');
|
if (!transaction) {
|
||||||
|
this.logger.error(`KYC transaction not found for stateId ${body.stateId}`);
|
||||||
|
throw new BadRequestException('KYC transaction not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.customerRepository.updateCustomer(customer.id, {
|
const customer = await this.findCustomerById(transaction.customerId);
|
||||||
kycStatus: body.status === 'SUCCESS' ? KycStatus.APPROVED : KycStatus.REJECTED,
|
const previousStatus = customer.kycStatus;
|
||||||
firstName: body.firstName,
|
|
||||||
lastName: body.lastName,
|
// Update transaction record
|
||||||
dateOfBirth: moment(body.dob, 'YYYYMMDD').toDate(),
|
await this.kycTransactionRepo.updateByStateId(body.stateId, {
|
||||||
nationalId: body.nationalId,
|
status: body.status,
|
||||||
nationalIdExpiry: moment(body.nationalIdExpiry, 'YYYYMMDD').toDate(),
|
callbackId: body.callbackId,
|
||||||
countryOfResidence: NumericToCountryIso[body.country],
|
completedAt: new Date(),
|
||||||
country: NumericToCountryIso[body.country],
|
|
||||||
gender: body.gender === 'M' ? Gender.MALE : Gender.FEMALE,
|
|
||||||
sourceOfIncome: body.incomeSource,
|
|
||||||
profession: body.professionTitle,
|
|
||||||
professionType: body.professionType,
|
|
||||||
isPep: body.isPep === 'Y',
|
|
||||||
city: body.city,
|
|
||||||
region: body.region,
|
|
||||||
neighborhood: body.neighborhood,
|
|
||||||
street: body.street,
|
|
||||||
building: body.building,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Update customer KYC status and external customer ID
|
||||||
|
const kycStatus = body.status === 'ONBOARDING_SUCCESS' ? KycStatus.APPROVED : KycStatus.REJECTED;
|
||||||
|
|
||||||
|
await this.customerRepository.updateCustomer(customer.id, {
|
||||||
|
kycStatus,
|
||||||
|
neoleapExternalCustomerId: body.entity.externalId,
|
||||||
|
rejectionReason: kycStatus === KycStatus.REJECTED ? 'KYC verification failed' : null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reload customer with updated data
|
||||||
|
const updatedCustomer = await this.findCustomerById(customer.id);
|
||||||
|
|
||||||
|
// Emit notification event
|
||||||
|
if (kycStatus === KycStatus.APPROVED) {
|
||||||
|
const event: IKycApprovedEvent = {
|
||||||
|
customer: updatedCustomer,
|
||||||
|
previousStatus,
|
||||||
|
timestamp: new Date(),
|
||||||
|
};
|
||||||
|
this.eventEmitter.emit(NOTIFICATION_EVENTS.KYC_APPROVED, event);
|
||||||
|
this.logger.log(`Emitted KYC_APPROVED event for customer ${customer.id}`);
|
||||||
|
} else {
|
||||||
|
const event: IKycRejectedEvent = {
|
||||||
|
customer: updatedCustomer,
|
||||||
|
previousStatus,
|
||||||
|
rejectionReason: updatedCustomer.rejectionReason || 'KYC verification failed',
|
||||||
|
timestamp: new Date(),
|
||||||
|
};
|
||||||
|
this.eventEmitter.emit(NOTIFICATION_EVENTS.KYC_REJECTED, event);
|
||||||
|
this.logger.log(`Emitted KYC_REJECTED event for customer ${customer.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(`KYC updated successfully for customer ${customer.id}, status: ${body.status}, externalId: ${body.entity.externalId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TO BE REMOVED: This function is for testing only and will be removed
|
// TO BE REMOVED: This function is for testing only and will be removed
|
||||||
@ -132,12 +212,6 @@ export class CustomerService {
|
|||||||
nationalId: '1089055972',
|
nationalId: '1089055972',
|
||||||
nationalIdExpiry: moment('2031-09-17').toDate(),
|
nationalIdExpiry: moment('2031-09-17').toDate(),
|
||||||
countryOfResidence: CountryIso.SAUDI_ARABIA,
|
countryOfResidence: CountryIso.SAUDI_ARABIA,
|
||||||
country: CountryIso.SAUDI_ARABIA,
|
|
||||||
region: 'Mecca',
|
|
||||||
city: 'AT Taif',
|
|
||||||
neighborhood: 'Al Faisaliah',
|
|
||||||
street: 'Al Faisaliah Street',
|
|
||||||
building: '4',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await User.update(userId, {
|
await User.update(userId, {
|
||||||
@ -149,6 +223,11 @@ export class CustomerService {
|
|||||||
return this.findCustomerById(userId);
|
return this.findCustomerById(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getKycOnboardMetadata() {
|
||||||
|
this.logger.log('Getting KYC onboard metadata');
|
||||||
|
return this.metadataService.getKycOnboardMetadata();
|
||||||
|
}
|
||||||
|
|
||||||
// TO BE REMOVED: This function is for testing only and will be removed
|
// TO BE REMOVED: This function is for testing only and will be removed
|
||||||
private generateSaudiPhoneNumber(): string {
|
private generateSaudiPhoneNumber(): string {
|
||||||
// Saudi mobile numbers are 9 digits, always starting with '5'
|
// Saudi mobile numbers are 9 digits, always starting with '5'
|
||||||
|
|||||||
@ -1 +1,2 @@
|
|||||||
export * from './customer.service';
|
export * from './customer.service';
|
||||||
|
export * from './metadata.service';
|
||||||
|
|||||||
105
src/customer/services/metadata.service.ts
Normal file
105
src/customer/services/metadata.service.ts
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { IncomeRange, IncomeSource, JobCategory, JobSector, PoiType } from '../enums';
|
||||||
|
import { KycMetadataResponseDto, MetadataOptionDto } from '../dtos/response';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MetadataService {
|
||||||
|
getKycOnboardMetadata(): KycMetadataResponseDto {
|
||||||
|
return {
|
||||||
|
poiTypes: this.enumToOptions(PoiType, {
|
||||||
|
[PoiType.IQA]: 'Iqama (Resident ID)',
|
||||||
|
[PoiType.NAT]: 'National ID',
|
||||||
|
}),
|
||||||
|
jobSectors: this.enumToOptions(JobSector, {
|
||||||
|
[JobSector.GOVERNMENT_SECTOR]: 'Government Sector',
|
||||||
|
[JobSector.HOME_MAKER]: 'Home Maker',
|
||||||
|
[JobSector.MILITARY]: 'Military',
|
||||||
|
[JobSector.PRIVATE_SECTOR]: 'Private Sector',
|
||||||
|
[JobSector.RETIRED]: 'Retired',
|
||||||
|
[JobSector.SELF_EMPLOYED]: 'Self Employed',
|
||||||
|
[JobSector.STUDENT]: 'Student',
|
||||||
|
[JobSector.HOUSEHOLD_LABOR]: 'Household Labor',
|
||||||
|
[JobSector.UNEMPLOYED]: 'Unemployed',
|
||||||
|
}),
|
||||||
|
incomeSources: this.enumToOptions(IncomeSource, {
|
||||||
|
[IncomeSource.SALARY]: 'Salary',
|
||||||
|
[IncomeSource.ANCESTRAL]: 'Ancestral/Inheritance',
|
||||||
|
[IncomeSource.REAL_ESTATE]: 'Real Estate',
|
||||||
|
[IncomeSource.INVESTMENT_RETURNS]: 'Investment Returns',
|
||||||
|
[IncomeSource.RENTAL_INCOME]: 'Rental Income',
|
||||||
|
[IncomeSource.OTHER]: 'Other',
|
||||||
|
}),
|
||||||
|
jobCategories: this.enumToOptions(JobCategory, {
|
||||||
|
[JobCategory.ASSISTANT_MINISTER]: 'Assistant Minister',
|
||||||
|
[JobCategory.DEPUTY_MINISTER]: 'Deputy Minister',
|
||||||
|
[JobCategory.UNDER_SECRETARY]: 'Under Secretary',
|
||||||
|
[JobCategory.GENERAL_MANAGER]: 'General Manager',
|
||||||
|
[JobCategory.CHAIRMAN]: 'Chairman',
|
||||||
|
[JobCategory.MANAGER]: 'Manager',
|
||||||
|
[JobCategory.PROFESSOR]: 'Professor',
|
||||||
|
[JobCategory.HEAD_OF_COURT]: 'Head of Court',
|
||||||
|
[JobCategory.JUDGE]: 'Judge',
|
||||||
|
[JobCategory.LAWYER]: 'Lawyer',
|
||||||
|
[JobCategory.SCIENTIST]: 'Scientist',
|
||||||
|
[JobCategory.NOTARY]: 'Notary',
|
||||||
|
[JobCategory.BUSINESSMAN]: 'Businessman',
|
||||||
|
[JobCategory.MERCHANT]: 'Merchant',
|
||||||
|
[JobCategory.PHARMACIST]: 'Pharmacist',
|
||||||
|
[JobCategory.DOCTOR]: 'Doctor',
|
||||||
|
[JobCategory.MEDICAL_TECHNICIAN]: 'Medical Technician',
|
||||||
|
[JobCategory.NURSE]: 'Nurse',
|
||||||
|
[JobCategory.ENGINEER]: 'Engineer',
|
||||||
|
[JobCategory.CHEMIST]: 'Chemist',
|
||||||
|
[JobCategory.CONTRACTOR]: 'Contractor',
|
||||||
|
[JobCategory.AUDITOR_ACCOUNTANT]: 'Auditor/Accountant',
|
||||||
|
[JobCategory.RESEARCHER]: 'Researcher',
|
||||||
|
[JobCategory.ACCOUNTANT]: 'Accountant',
|
||||||
|
[JobCategory.JOURNALIST]: 'Journalist',
|
||||||
|
[JobCategory.DESIGNER]: 'Designer',
|
||||||
|
[JobCategory.COMPUTER_SPECIALIST]: 'Computer Specialist',
|
||||||
|
[JobCategory.TRANSLATOR]: 'Translator',
|
||||||
|
[JobCategory.TEACHER]: 'Teacher',
|
||||||
|
[JobCategory.PILOT]: 'Pilot',
|
||||||
|
[JobCategory.HOST]: 'Host',
|
||||||
|
[JobCategory.OFFICER]: 'Officer',
|
||||||
|
[JobCategory.SOLDIER]: 'Soldier',
|
||||||
|
[JobCategory.RETIRED]: 'Retired',
|
||||||
|
[JobCategory.SALESMAN]: 'Salesman',
|
||||||
|
[JobCategory.AUTHOR]: 'Author',
|
||||||
|
[JobCategory.CRAFTSMAN]: 'Craftsman',
|
||||||
|
[JobCategory.SECURITY]: 'Security',
|
||||||
|
[JobCategory.LABORER]: 'Laborer',
|
||||||
|
[JobCategory.DRIVER]: 'Driver',
|
||||||
|
[JobCategory.FARMER]: 'Farmer',
|
||||||
|
[JobCategory.HOUSEWIFE]: 'Housewife',
|
||||||
|
[JobCategory.DIPLOMAT]: 'Diplomat',
|
||||||
|
[JobCategory.STUDENT]: 'Student',
|
||||||
|
[JobCategory.FREELANCER]: 'Freelancer',
|
||||||
|
[JobCategory.SHEPHERD]: 'Shepherd',
|
||||||
|
[JobCategory.HOUSEMAID_OR_BABYSITTER]: 'Housemaid/Babysitter',
|
||||||
|
[JobCategory.CAPTAIN]: 'Captain',
|
||||||
|
[JobCategory.AMBASSADOR]: 'Ambassador',
|
||||||
|
[JobCategory.MARKETING]: 'Marketing',
|
||||||
|
[JobCategory.CONSULTING]: 'Consulting',
|
||||||
|
[JobCategory.SUPERVISOR]: 'Supervisor',
|
||||||
|
[JobCategory.BANKER]: 'Banker',
|
||||||
|
[JobCategory.BODYGUARD_OR_PERSONAL_ASSISTANT]: 'Bodyguard/Personal Assistant',
|
||||||
|
}),
|
||||||
|
incomeRanges: this.enumToOptions(IncomeRange, {
|
||||||
|
[IncomeRange.BELOW_2000]: 'SAR 2,000 and below',
|
||||||
|
[IncomeRange.RANGE_2000_5000]: 'SAR 2,000 to 5,000',
|
||||||
|
[IncomeRange.RANGE_5000_10000]: 'SAR 5,000 to 10,000',
|
||||||
|
[IncomeRange.RANGE_10000_20000]: 'SAR 10,000 to 20,000',
|
||||||
|
[IncomeRange.ABOVE_20000]: 'SAR 20,000 and above',
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private enumToOptions(enumObj: any, labels: Record<string, string>): MetadataOptionDto[] {
|
||||||
|
return Object.keys(enumObj).map((key) => ({
|
||||||
|
value: enumObj[key],
|
||||||
|
label: labels[enumObj[key]] || enumObj[key],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
65
src/customer/validators/poi-number.validator.ts
Normal file
65
src/customer/validators/poi-number.validator.ts
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import {
|
||||||
|
registerDecorator,
|
||||||
|
ValidationOptions,
|
||||||
|
ValidatorConstraint,
|
||||||
|
ValidatorConstraintInterface,
|
||||||
|
ValidationArguments,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { PoiType } from '../enums';
|
||||||
|
|
||||||
|
@ValidatorConstraint({ name: 'IsValidPoiNumber', async: false })
|
||||||
|
export class IsValidPoiNumberConstraint implements ValidatorConstraintInterface {
|
||||||
|
validate(poiNumber: string, args: ValidationArguments) {
|
||||||
|
const object = args.object as any;
|
||||||
|
const poiType = object.poiType;
|
||||||
|
|
||||||
|
if (!poiNumber || !poiType) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Saudi National ID: 10 digits, typically starts with 1 or 2
|
||||||
|
const nationalIdPattern = /^[12]\d{9}$/;
|
||||||
|
|
||||||
|
// Iqama (Resident ID): 10 digits, typically starts with other numbers (not 1 or 2)
|
||||||
|
const iqamaPattern = /^[3-9]\d{9}$/;
|
||||||
|
|
||||||
|
if (poiType === PoiType.NAT) {
|
||||||
|
return nationalIdPattern.test(poiNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (poiType === PoiType.IQA) {
|
||||||
|
return iqamaPattern.test(poiNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultMessage(args: ValidationArguments) {
|
||||||
|
const object = args.object as any;
|
||||||
|
const poiType = object.poiType;
|
||||||
|
|
||||||
|
if (poiType === PoiType.NAT) {
|
||||||
|
return 'National ID must be 10 digits and start with 1 or 2';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (poiType === PoiType.IQA) {
|
||||||
|
return 'Iqama number must be 10 digits and start with 3-9';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Invalid POI number format';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IsValidPoiNumber(validationOptions?: ValidationOptions) {
|
||||||
|
return function (object: Object, propertyName: string) {
|
||||||
|
registerDecorator({
|
||||||
|
target: object.constructor,
|
||||||
|
propertyName: propertyName,
|
||||||
|
options: validationOptions,
|
||||||
|
constraints: [],
|
||||||
|
validator: IsValidPoiNumberConstraint,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -0,0 +1,32 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class AddKycFieldsAndTransactions1765804942393 implements MigrationInterface {
|
||||||
|
name = 'AddKycFieldsAndTransactions1765804942393'
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`CREATE TABLE "kyc_transactions" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "customer_id" uuid NOT NULL, "user_id" uuid NOT NULL, "state_id" character varying(255) NOT NULL, "external_customer_id" character varying(255), "nafath_random_code" character varying(10), "status" character varying(50) NOT NULL DEFAULT 'INITIATED', "form_data" jsonb NOT NULL, "callback_id" character varying(255), "initiated_at" TIMESTAMP NOT NULL DEFAULT now(), "completed_at" TIMESTAMP, "expires_at" TIMESTAMP, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "UQ_231ce1d974b00919a8202e9ca3f" UNIQUE ("state_id"), CONSTRAINT "PK_aa56e3feebd4323c684ca146418" PRIMARY KEY ("id"))`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "neoleap_external_customer_id" character varying(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "job_sector" character varying(100)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "employer" character varying(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "income_source" character varying(100)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "job_category" character varying(100)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "income_range" character varying(100)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "mobile_number" character varying(20)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" ADD CONSTRAINT "FK_7651cf2e3ae6381377d8b9ed963" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" ADD CONSTRAINT "FK_336a3791fd94d386e5c428850db" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" DROP CONSTRAINT "FK_336a3791fd94d386e5c428850db"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" DROP CONSTRAINT "FK_7651cf2e3ae6381377d8b9ed963"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "mobile_number"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "income_range"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "job_category"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "income_source"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "employer"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "job_sector"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "neoleap_external_customer_id"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "kyc_transactions"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class AddNationalIdToKycTransactions1765877128065 implements MigrationInterface {
|
||||||
|
name = 'AddNationalIdToKycTransactions1765877128065'
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
// Add column as nullable first (to handle existing records)
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" ADD "national_id" character varying(50)`);
|
||||||
|
|
||||||
|
// Backfill existing records from form_data->poiNumber
|
||||||
|
await queryRunner.query(`
|
||||||
|
UPDATE "kyc_transactions"
|
||||||
|
SET "national_id" = form_data->>'poiNumber'
|
||||||
|
WHERE "national_id" IS NULL AND form_data->>'poiNumber' IS NOT NULL
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Now make it NOT NULL with a default empty string for safety
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" ALTER COLUMN "national_id" SET DEFAULT ''`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" ALTER COLUMN "national_id" SET NOT NULL`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "kyc_transactions" DROP COLUMN "national_id"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
23
src/db/migrations/1765891028260-RemoveOldCustomerColumns.ts
Normal file
23
src/db/migrations/1765891028260-RemoveOldCustomerColumns.ts
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class RemoveOldCustomerColumns1765891028260 implements MigrationInterface {
|
||||||
|
name = 'RemoveOldCustomerColumns1765891028260';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
// Remove duplicate/unused columns that were replaced by KYC-specific fields
|
||||||
|
// source_of_income -> replaced by income_source
|
||||||
|
// profession -> replaced by job_sector
|
||||||
|
// profession_type -> replaced by job_category
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "source_of_income"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "profession"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "profession_type"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
// Restore columns if migration is rolled back
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "source_of_income" character varying(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "profession" character varying(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "profession_type" character varying(255)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
26
src/db/migrations/1765975126402-RemoveAddressColumns.ts
Normal file
26
src/db/migrations/1765975126402-RemoveAddressColumns.ts
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||||
|
|
||||||
|
export class RemoveAddressColumns1765975126402 implements MigrationInterface {
|
||||||
|
name = 'RemoveAddressColumns1765975126402';
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
// Drop address columns from customers table
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "country"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "region"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "city"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "neighborhood"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "street"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN IF EXISTS "building"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
// Re-add address columns in case of rollback
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "country" varchar(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "region" varchar(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "city" varchar(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "neighborhood" varchar(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "street" varchar(255)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "customers" ADD "building" varchar(255)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -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"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
18
src/db/migrations/1768395622276-AddTimezoneFields.ts
Normal file
18
src/db/migrations/1768395622276-AddTimezoneFields.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class AddTimezoneFields1768395622276 implements MigrationInterface {
|
||||||
|
name = 'AddTimezoneFields1768395622276'
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "users" ADD "timezone" character varying(50)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "devices" ADD "timezone" character varying(50)`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "users" ALTER COLUMN "is_push_enabled" SET DEFAULT true`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "users" ALTER COLUMN "is_push_enabled" SET DEFAULT false`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "devices" DROP COLUMN "timezone"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "timezone"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -5,4 +5,10 @@ export * from './1757349525708-create-money-requests-table';
|
|||||||
export * from './1757433339849-add-reservation-amount-to-account-entity';
|
export * from './1757433339849-add-reservation-amount-to-account-entity';
|
||||||
export * from './1757915357218-add-deleted-at-column-to-junior';
|
export * from './1757915357218-add-deleted-at-column-to-junior';
|
||||||
export * from './1760869651296-AddMerchantInfoToTransactions';
|
export * from './1760869651296-AddMerchantInfoToTransactions';
|
||||||
export * from './1761032305682-AddUniqueConstraintToUserEmail';
|
export * from './1761032305682-AddUniqueConstraintToUserEmail';
|
||||||
|
export * from './1767172707881-AddDataColumnToNotifications';
|
||||||
|
export * from './1765804942393-AddKycFieldsAndTransactions';
|
||||||
|
export * from './1765877128065-AddNationalIdToKycTransactions';
|
||||||
|
export * from './1765891028260-RemoveOldCustomerColumns';
|
||||||
|
export * from './1765975126402-RemoveAddressColumns';
|
||||||
|
export * from './1768395622276-AddTimezoneFields';
|
||||||
@ -19,6 +19,10 @@
|
|||||||
"TOKEN_EXPIRED": "رمز المستخدم منتهي الصلاحية."
|
"TOKEN_EXPIRED": "رمز المستخدم منتهي الصلاحية."
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"QR": {
|
||||||
|
"CODE_USED_OR_EXPIRED": "تم استخدام رمز QR مسبقًا أو انتهت صلاحيته."
|
||||||
|
},
|
||||||
|
|
||||||
"USER": {
|
"USER": {
|
||||||
"PHONE_ALREADY_VERIFIED": "تم التحقق من رقم الهاتف بالفعل.",
|
"PHONE_ALREADY_VERIFIED": "تم التحقق من رقم الهاتف بالفعل.",
|
||||||
"EMAIL_ALREADY_VERIFIED": "تم التحقق من عنوان البريد الإلكتروني بالفعل.",
|
"EMAIL_ALREADY_VERIFIED": "تم التحقق من عنوان البريد الإلكتروني بالفعل.",
|
||||||
@ -106,5 +110,48 @@
|
|||||||
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
|
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
|
||||||
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر.",
|
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر.",
|
||||||
"NOT_FOUND": "لم يتم العثور على البطاقة."
|
"NOT_FOUND": "لم يتم العثور على البطاقة."
|
||||||
|
},
|
||||||
|
"NOTIFICATION": {
|
||||||
|
"CHILD_TOP_UP_TITLE": "تم إضافة رصيد",
|
||||||
|
"CHILD_TOP_UP_MESSAGE": "تمت إضافة {amount} {currency} إلى بطاقتك. إجمالي الرصيد: {balance} {currency}",
|
||||||
|
"CHILD_INTERNAL_TRANSFER_TITLE": "تم إضافة رصيد",
|
||||||
|
"CHILD_INTERNAL_TRANSFER_MESSAGE": "تمت إضافة {amount} {currency} إلى بطاقتك. إجمالي الرصيد: {balance} {currency}",
|
||||||
|
"PARENT_INTERNAL_TRANSFER_TITLE": "اكتمل التحويل",
|
||||||
|
"PARENT_INTERNAL_TRANSFER_MESSAGE": "تم تحويل {amount} {currency} إلى بطاقة {childName}. رصيد {childName}: {balance} {currency}",
|
||||||
|
"CHILD_SPENDING_TITLE": "عملية شراء ناجحة",
|
||||||
|
"CHILD_SPENDING_MESSAGE": "قمت بإنفاق {amount} {currency} في {merchant}",
|
||||||
|
"PARENT_SPENDING_TITLE": "تنبيه صرف",
|
||||||
|
"PARENT_SPENDING_MESSAGE": "قام {childName} بإنفاق {amount} {currency} في {merchant}. الرصيد المتبقي: {balance} {currency}",
|
||||||
|
"YOUR_CHILD": "طفلك",
|
||||||
|
"MONEY_REQUEST_CREATED_TITLE": "طلب مبلغ مالي",
|
||||||
|
"MONEY_REQUEST_CREATED_MESSAGE": "طلب {childName} مبلغ {amount} {currency} لـ {reason}",
|
||||||
|
"MONEY_REQUEST_APPROVED_TITLE": "تمت الموافقة على طلب المال",
|
||||||
|
"MONEY_REQUEST_APPROVED_MESSAGE": "تمت الموافقة على طلبك بمبلغ {amount} {currency}. تمت إضافة المال إلى حسابك.",
|
||||||
|
"MONEY_REQUEST_DECLINED_TITLE": "تم رفض طلب المال",
|
||||||
|
"MONEY_REQUEST_DECLINED_MESSAGE": "تم رفض طلبك بمبلغ {amount} {currency}. السبب: {reason}",
|
||||||
|
"KYC_APPROVED_TITLE": "تمت الموافقة على التحقق من الهوية",
|
||||||
|
"KYC_APPROVED_MESSAGE": "تمت الموافقة على التحقق من هويتك. يمكنك الآن استخدام جميع ميزات التطبيق.",
|
||||||
|
"KYC_REJECTED_TITLE": "تم رفض التحقق من الهوية",
|
||||||
|
"KYC_REJECTED_MESSAGE": "تم رفض التحقق من هويتك. السبب: {reason}. يرجى مراجعة معلوماتك والمحاولة مرة أخرى.",
|
||||||
|
"CARD_CREATED_TITLE": "تم إنشاء البطاقة",
|
||||||
|
"CARD_CREATED_MESSAGE": "تم إنشاء بطاقتك التي تنتهي بـ {lastFourDigits} بنجاح. يمكنك البدء في استخدامها بمجرد تفعيلها.",
|
||||||
|
"CARD_BLOCKED_TITLE": "تم حظر البطاقة",
|
||||||
|
"CARD_BLOCKED_MESSAGE": "تم حظر بطاقتك التي تنتهي بـ {lastFourDigits}. السبب: {reason}. يرجى الاتصال بالدعم للحصول على المساعدة.",
|
||||||
|
"PROFILE_UPDATED_TITLE": "تم تحديث الملف الشخصي",
|
||||||
|
"PROFILE_UPDATED_MESSAGE": "تم تحديث ملفك الشخصي. التغييرات: {fields}",
|
||||||
|
"PROFILE_EMAIL_UPDATED_TITLE": "تم تحديث البريد الإلكتروني",
|
||||||
|
"PROFILE_EMAIL_UPDATED_MESSAGE": "تم تحديث بريدك الإلكتروني إلى {email}. يرجى التحقق من عنوان بريدك الإلكتروني الجديد.",
|
||||||
|
"PROFILE_PASSWORD_UPDATED_TITLE": "تم تحديث كلمة المرور",
|
||||||
|
"PROFILE_PASSWORD_UPDATED_MESSAGE": "تم تحديث كلمة المرور بنجاح. إذا لم تقم بهذا التغيير، يرجى الاتصال بالدعم فوراً.",
|
||||||
|
"PROFILE_PICTURE_UPDATED_TITLE": "تم تحديث صورة الملف الشخصي",
|
||||||
|
"PROFILE_PICTURE_UPDATED_MESSAGE": "تم تحديث صورة ملفك الشخصي بنجاح.",
|
||||||
|
"PROFILE_NAME_UPDATED_TITLE": "تم تحديث الاسم",
|
||||||
|
"PROFILE_NAME_UPDATED_MESSAGE": "تم تحديث اسمك بنجاح.",
|
||||||
|
"MAINTENANCE_ALERT_TITLE": "صيانة مجدولة",
|
||||||
|
"MAINTENANCE_ALERT_MESSAGE": "{message}",
|
||||||
|
"TRANSACTION_FAILED_TITLE": "فشلت المعاملة",
|
||||||
|
"TRANSACTION_FAILED_MESSAGE": "لم يتم إكمال معاملتك. السبب: {reason}. يرجى المحاولة مرة أخرى أو الاتصال بالدعم إذا استمرت المشكلة.",
|
||||||
|
"SUSPICIOUS_LOGIN_TITLE": "تم اكتشاف تسجيل دخول مشبوه",
|
||||||
|
"SUSPICIOUS_LOGIN_MESSAGE": "اكتشفنا محاولة تسجيل دخول من {location} ({ipAddress}) باستخدام {device}. إذا لم تكن أنت، يرجى تغيير كلمة المرور فوراً والاتصال بالدعم."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,6 +19,10 @@
|
|||||||
"TOKEN_EXPIRED": "The user token has expired."
|
"TOKEN_EXPIRED": "The user token has expired."
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"QR": {
|
||||||
|
"CODE_USED_OR_EXPIRED": "The QR code has already been used or expired."
|
||||||
|
},
|
||||||
|
|
||||||
"USER": {
|
"USER": {
|
||||||
"PHONE_ALREADY_VERIFIED": "The phone number has already been verified.",
|
"PHONE_ALREADY_VERIFIED": "The phone number has already been verified.",
|
||||||
"EMAIL_ALREADY_VERIFIED": "The email address has already been verified.",
|
"EMAIL_ALREADY_VERIFIED": "The email address has already been verified.",
|
||||||
@ -105,5 +109,48 @@
|
|||||||
"INSUFFICIENT_BALANCE": "The card does not have sufficient balance to complete this transfer.",
|
"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.",
|
"DOES_NOT_BELONG_TO_GUARDIAN": "The card does not belong to the guardian.",
|
||||||
"NOT_FOUND": "The card was not found."
|
"NOT_FOUND": "The card was not found."
|
||||||
|
},
|
||||||
|
"NOTIFICATION": {
|
||||||
|
"CHILD_TOP_UP_TITLE": "Funds Credited",
|
||||||
|
"CHILD_TOP_UP_MESSAGE": "{amount} {currency} has been added to your card. Total balance: {balance} {currency}",
|
||||||
|
"CHILD_INTERNAL_TRANSFER_TITLE": "Funds Credited",
|
||||||
|
"CHILD_INTERNAL_TRANSFER_MESSAGE": "{amount} {currency} has been added to your card. Total balance: {balance} {currency}",
|
||||||
|
"PARENT_INTERNAL_TRANSFER_TITLE": "Internal Transfer Completed",
|
||||||
|
"PARENT_INTERNAL_TRANSFER_MESSAGE": "{amount} {currency} has been transferred to {childName}'s card. {childName}'s balance is {balance} {currency}",
|
||||||
|
"CHILD_SPENDING_TITLE": "Purchase Successful",
|
||||||
|
"CHILD_SPENDING_MESSAGE": "You spent {amount} {currency} at {merchant}",
|
||||||
|
"PARENT_SPENDING_TITLE": "Spending Alert",
|
||||||
|
"PARENT_SPENDING_MESSAGE": "{childName} spent {amount} {currency} at {merchant}. Remaining balance: {balance} {currency}",
|
||||||
|
"YOUR_CHILD": "Your child",
|
||||||
|
"MONEY_REQUEST_CREATED_TITLE": "Money Request",
|
||||||
|
"MONEY_REQUEST_CREATED_MESSAGE": "{childName} has requested {amount} {currency} for {reason}.",
|
||||||
|
"MONEY_REQUEST_APPROVED_TITLE": "Money Request Approved",
|
||||||
|
"MONEY_REQUEST_APPROVED_MESSAGE": "Your request for {amount} {currency} has been approved. The money has been added to your account.",
|
||||||
|
"MONEY_REQUEST_DECLINED_TITLE": "Money Request Declined",
|
||||||
|
"MONEY_REQUEST_DECLINED_MESSAGE": "Your request for {amount} {currency} has been declined. Reason: {reason}",
|
||||||
|
"KYC_APPROVED_TITLE": "KYC Verification Approved",
|
||||||
|
"KYC_APPROVED_MESSAGE": "Your KYC verification has been approved. You can now use all features of the app.",
|
||||||
|
"KYC_REJECTED_TITLE": "KYC Verification Rejected",
|
||||||
|
"KYC_REJECTED_MESSAGE": "Your KYC verification has been rejected. Reason: {reason}. Please review your information and try again.",
|
||||||
|
"CARD_CREATED_TITLE": "Card Created",
|
||||||
|
"CARD_CREATED_MESSAGE": "Your card ending in {lastFourDigits} has been created successfully. You can start using it once it's activated.",
|
||||||
|
"CARD_BLOCKED_TITLE": "Card Blocked",
|
||||||
|
"CARD_BLOCKED_MESSAGE": "Your card ending in {lastFourDigits} has been blocked. Reason: {reason}. Please contact support for assistance.",
|
||||||
|
"PROFILE_UPDATED_TITLE": "Profile Updated",
|
||||||
|
"PROFILE_UPDATED_MESSAGE": "Your profile has been updated. Changes: {fields}",
|
||||||
|
"PROFILE_EMAIL_UPDATED_TITLE": "Email Updated",
|
||||||
|
"PROFILE_EMAIL_UPDATED_MESSAGE": "Your email has been updated to {email}. Please verify your new email address.",
|
||||||
|
"PROFILE_PASSWORD_UPDATED_TITLE": "Password Updated",
|
||||||
|
"PROFILE_PASSWORD_UPDATED_MESSAGE": "Your password has been successfully updated. If you did not make this change, please contact support immediately.",
|
||||||
|
"PROFILE_PICTURE_UPDATED_TITLE": "Profile Picture Updated",
|
||||||
|
"PROFILE_PICTURE_UPDATED_MESSAGE": "Your profile picture has been updated successfully.",
|
||||||
|
"PROFILE_NAME_UPDATED_TITLE": "Name Updated",
|
||||||
|
"PROFILE_NAME_UPDATED_MESSAGE": "Your name has been updated successfully.",
|
||||||
|
"MAINTENANCE_ALERT_TITLE": "Scheduled Maintenance",
|
||||||
|
"MAINTENANCE_ALERT_MESSAGE": "{message}",
|
||||||
|
"TRANSACTION_FAILED_TITLE": "Transaction Failed",
|
||||||
|
"TRANSACTION_FAILED_MESSAGE": "Your transaction could not be completed. Reason: {reason}. Please try again or contact support if the issue persists.",
|
||||||
|
"SUSPICIOUS_LOGIN_TITLE": "Suspicious Login Detected",
|
||||||
|
"SUSPICIOUS_LOGIN_MESSAGE": "We detected a login attempt from {location} ({ipAddress}) using {device}. If this was not you, please change your password immediately and contact support."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,6 +5,7 @@ import { Roles } from '~/auth/enums';
|
|||||||
import { CardService, TransactionService } from '~/card/services';
|
import { CardService, TransactionService } from '~/card/services';
|
||||||
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
import { PageOptionsRequestDto } from '~/core/dtos';
|
||||||
|
import { ErrorCategory } from '~/core/enums';
|
||||||
import { setIf } from '~/core/utils';
|
import { setIf } from '~/core/utils';
|
||||||
import { CustomerService } from '~/customer/services';
|
import { CustomerService } from '~/customer/services';
|
||||||
import { DocumentService, OciService } from '~/document/services';
|
import { DocumentService, OciService } from '~/document/services';
|
||||||
@ -113,7 +114,28 @@ export class JuniorService {
|
|||||||
}
|
}
|
||||||
junior.customer.user.email = body.email;
|
junior.customer.user.email = body.email;
|
||||||
}
|
}
|
||||||
setIf(user, 'profilePictureId', body.profilePictureId);
|
// Update profile picture: ensure FK and relation are consistent to avoid TypeORM overriding the FK
|
||||||
|
if (typeof body.profilePictureId !== 'undefined') {
|
||||||
|
if (body.profilePictureId) {
|
||||||
|
const document = await this.documentService.findDocumentById(body.profilePictureId);
|
||||||
|
if (!document) {
|
||||||
|
this.logger.error(`Document with id ${body.profilePictureId} not found`);
|
||||||
|
throw new BadRequestException('DOCUMENT.NOT_FOUND');
|
||||||
|
}
|
||||||
|
if (document.createdById !== juniorId) {
|
||||||
|
this.logger.error(
|
||||||
|
`Document with id ${body.profilePictureId} does not belong to user ${juniorId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
user.profilePictureId = body.profilePictureId;
|
||||||
|
// assign relation to keep it consistent with FK during save
|
||||||
|
user.profilePicture = document as any;
|
||||||
|
} else {
|
||||||
|
// if empty string provided (unlikely), clear relation and FK
|
||||||
|
user.profilePicture = null as any;
|
||||||
|
user.profilePictureId = null as any;
|
||||||
|
}
|
||||||
|
}
|
||||||
setIf(user, 'firstName', body.firstName);
|
setIf(user, 'firstName', body.firstName);
|
||||||
setIf(user, 'lastName', body.lastName);
|
setIf(user, 'lastName', body.lastName);
|
||||||
|
|
||||||
@ -125,7 +147,7 @@ export class JuniorService {
|
|||||||
setIf(junior, 'relationship', body.relationship);
|
setIf(junior, 'relationship', body.relationship);
|
||||||
await Promise.all([junior.save(), customer.save(), user.save()]);
|
await Promise.all([junior.save(), customer.save(), user.save()]);
|
||||||
this.logger.log(`Junior ${juniorId} updated successfully`);
|
this.logger.log(`Junior ${juniorId} updated successfully`);
|
||||||
return junior;
|
return this.findJuniorById(juniorId, false, guardianId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
@ -158,7 +180,14 @@ export class JuniorService {
|
|||||||
async validateToken(token: string) {
|
async validateToken(token: string) {
|
||||||
this.logger.log(`Validating token ${token}`);
|
this.logger.log(`Validating token ${token}`);
|
||||||
const juniorId = await this.userTokenService.validateToken(token, UserType.JUNIOR);
|
const juniorId = await this.userTokenService.validateToken(token, UserType.JUNIOR);
|
||||||
return this.findJuniorById(juniorId!, true);
|
const junior = await this.findJuniorById(juniorId!, true);
|
||||||
|
|
||||||
|
if (junior.customer?.user?.password) {
|
||||||
|
this.logger.error(`Token ${token} already used for junior ${juniorId}`);
|
||||||
|
throw new BadRequestException({ message: 'QR.CODE_USED_OR_EXPIRED', category: ErrorCategory.BUSINESS_ERROR });
|
||||||
|
}
|
||||||
|
|
||||||
|
return junior;
|
||||||
}
|
}
|
||||||
|
|
||||||
async generateToken(juniorId: string) {
|
async generateToken(juniorId: string) {
|
||||||
|
|||||||
@ -56,7 +56,35 @@ export class MoneyRequestsRepository {
|
|||||||
}
|
}
|
||||||
return this.moneyRequestRepository.findOne({
|
return this.moneyRequestRepository.findOne({
|
||||||
where: whereCondition,
|
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',
|
||||||
|
'junior.customer.cards',
|
||||||
|
'junior.customer.cards.account',
|
||||||
|
'guardian',
|
||||||
|
'guardian.customer',
|
||||||
|
'guardian.customer.user',
|
||||||
|
],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,13 @@
|
|||||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||||
import { Transactional } from 'typeorm-transactional';
|
import { Transactional } from 'typeorm-transactional';
|
||||||
import { Roles } from '~/auth/enums';
|
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 { OciService } from '~/document/services';
|
||||||
import { Junior } from '~/junior/entities/junior.entity';
|
import { Junior } from '~/junior/entities/junior.entity';
|
||||||
import { JuniorService } from '~/junior/services';
|
import { JuniorService } from '~/junior/services';
|
||||||
@ -16,10 +23,19 @@ export class MoneyRequestsService {
|
|||||||
private readonly moneyRequestsRepository: MoneyRequestsRepository,
|
private readonly moneyRequestsRepository: MoneyRequestsRepository,
|
||||||
private readonly juniorService: JuniorService,
|
private readonly juniorService: JuniorService,
|
||||||
private readonly ociService: OciService,
|
private readonly ociService: OciService,
|
||||||
|
private readonly eventEmitter: EventEmitter2,
|
||||||
) {}
|
) {}
|
||||||
async createMoneyRequest(juniorId: string, body: CreateMoneyRequestDto) {
|
async createMoneyRequest(juniorId: string, body: CreateMoneyRequestDto) {
|
||||||
const junior = await this.juniorService.findJuniorById(juniorId);
|
const junior = await this.juniorService.findJuniorById(juniorId);
|
||||||
const moneyRequest = await this.moneyRequestsRepository.createMoneyRequest(junior.id, junior.guardianId, body);
|
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);
|
return this.findById(moneyRequest.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,6 +79,13 @@ export class MoneyRequestsService {
|
|||||||
moneyRequest.guardianId,
|
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(
|
async rejectMoneyRequest(
|
||||||
@ -85,6 +108,14 @@ export class MoneyRequestsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.moneyRequestsRepository.rejectMoneyRequest(id, rejectionReasondto?.rejectionReason);
|
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[]) {
|
private async prepareJuniorImages(juniors: Junior[]) {
|
||||||
|
|||||||
@ -1,15 +1,15 @@
|
|||||||
import { Body, Controller, Get, Headers, HttpCode, HttpStatus, Patch, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Get, HttpCode, HttpStatus, Patch, UseGuards } from '@nestjs/common';
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
import { VerifyOtpRequestDto } from '~/auth/dtos/request';
|
import { VerifyOtpRequestDto } from '~/auth/dtos/request';
|
||||||
import { UserResponseDto } from '~/auth/dtos/response';
|
import { UserResponseDto } from '~/auth/dtos/response';
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
import { IJwtPayload } from '~/auth/interfaces';
|
||||||
import { DEVICE_ID_HEADER } from '~/common/constants';
|
|
||||||
import { AuthenticatedUser } from '~/common/decorators';
|
import { AuthenticatedUser } from '~/common/decorators';
|
||||||
import { AccessTokenGuard } from '~/common/guards';
|
import { AccessTokenGuard } from '~/common/guards';
|
||||||
import { ApiDataResponse } from '~/core/decorators';
|
import { ApiDataResponse } from '~/core/decorators';
|
||||||
import { ResponseFactory } from '~/core/utils';
|
import { ResponseFactory } from '~/core/utils';
|
||||||
import { UpdateNotificationsSettingsRequestDto, UpdateUserRequestDto } from '../dtos/request';
|
import { UpdateNotificationsSettingsRequestDto, UpdateUserRequestDto } from '../dtos/request';
|
||||||
import { UpdateEmailRequestDto } from '../dtos/request/update-email.request.dto';
|
import { UpdateEmailRequestDto } from '../dtos/request/update-email.request.dto';
|
||||||
|
import { NotificationsSettingsResponseDto } from '../dtos/response/notifications-settings.response.dto';
|
||||||
import { UserService } from '../services';
|
import { UserService } from '../services';
|
||||||
|
|
||||||
@Controller('profile')
|
@Controller('profile')
|
||||||
@ -45,13 +45,22 @@ export class UserController {
|
|||||||
return this.userService.verifyEmail(user.sub, otp);
|
return this.userService.verifyEmail(user.sub, otp);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('notifications-settings')
|
||||||
|
@HttpCode(HttpStatus.OK)
|
||||||
|
@ApiDataResponse(NotificationsSettingsResponseDto)
|
||||||
|
async getNotificationSettings(@AuthenticatedUser() { sub }: IJwtPayload) {
|
||||||
|
const user = await this.userService.findUserOrThrow({ id: sub });
|
||||||
|
return ResponseFactory.data(new NotificationsSettingsResponseDto({
|
||||||
|
isPushEnabled: user.isPushEnabled ?? true,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
@Patch('notifications-settings')
|
@Patch('notifications-settings')
|
||||||
@HttpCode(HttpStatus.NO_CONTENT)
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
async updateNotificationSettings(
|
async updateNotificationSettings(
|
||||||
@AuthenticatedUser() user: IJwtPayload,
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
@Body() data: UpdateNotificationsSettingsRequestDto,
|
@Body() data: UpdateNotificationsSettingsRequestDto,
|
||||||
@Headers(DEVICE_ID_HEADER) deviceId: string,
|
|
||||||
) {
|
) {
|
||||||
return this.userService.updateNotificationSettings(user.sub, data, deviceId);
|
return this.userService.updateNotificationSettings(user.sub, data, data.deviceId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,23 +2,19 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|||||||
import { IsBoolean, IsOptional, IsString, ValidateIf } from 'class-validator';
|
import { IsBoolean, IsOptional, IsString, ValidateIf } from 'class-validator';
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
export class UpdateNotificationsSettingsRequestDto {
|
export class UpdateNotificationsSettingsRequestDto {
|
||||||
@ApiProperty()
|
@ApiPropertyOptional({ example: true, description: 'Enable/disable push notifications (default: true)', default: true })
|
||||||
@IsBoolean({ message: i18n('validation.IsBoolean', { path: 'general', property: 'customer.isEmailEnabled' }) })
|
|
||||||
@IsOptional()
|
|
||||||
isEmailEnabled!: boolean;
|
|
||||||
|
|
||||||
@ApiProperty()
|
|
||||||
@IsBoolean({ message: i18n('validation.IsBoolean', { path: 'general', property: 'customer.isPushEnabled' }) })
|
@IsBoolean({ message: i18n('validation.IsBoolean', { path: 'general', property: 'customer.isPushEnabled' }) })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
isPushEnabled!: boolean;
|
isPushEnabled?: boolean;
|
||||||
|
|
||||||
@ApiProperty()
|
@ApiPropertyOptional({ example: 'cXYzABC:APA91bH...', description: 'Firebase Cloud Messaging token (required if enabling push)' })
|
||||||
@IsBoolean({ message: i18n('validation.IsBoolean', { path: 'general', property: 'customer.isSmsEnabled' }) })
|
|
||||||
@IsOptional()
|
|
||||||
isSmsEnabled!: boolean;
|
|
||||||
|
|
||||||
@ApiPropertyOptional()
|
|
||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.fcmToken' }) })
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.fcmToken' }) })
|
||||||
@ValidateIf((o) => o.isPushEnabled)
|
@ValidateIf((o) => o.isPushEnabled !== false)
|
||||||
|
@IsOptional()
|
||||||
fcmToken?: string;
|
fcmToken?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'device-123', description: 'Device identifier (optional, will be found automatically if not provided)' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.deviceId' }) })
|
||||||
|
deviceId?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -34,4 +34,12 @@ export class UpdateUserRequestDto {
|
|||||||
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.dateOfBirth' }) })
|
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.dateOfBirth' }) })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
dateOfBirth!: Date;
|
dateOfBirth!: Date;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: 'Asia/Riyadh',
|
||||||
|
description: 'User preferred timezone for reports/statements (e.g., "Asia/Riyadh", "America/New_York"). Leave empty or "Auto" to use device timezone.',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'user.timezone' }) })
|
||||||
|
timezone?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,10 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class NotificationsSettingsResponseDto {
|
||||||
|
@ApiProperty({ example: true, description: 'Push notifications enabled/disabled' })
|
||||||
|
isPushEnabled!: boolean;
|
||||||
|
|
||||||
|
constructor(data: { isPushEnabled: boolean }) {
|
||||||
|
this.isPushEnabled = data.isPushEnabled;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -18,6 +18,9 @@ export class Device {
|
|||||||
@Column('varchar', { name: 'fcm_token', nullable: true })
|
@Column('varchar', { name: 'fcm_token', nullable: true })
|
||||||
fcmToken?: string | null;
|
fcmToken?: string | null;
|
||||||
|
|
||||||
|
@Column('varchar', { name: 'timezone', nullable: true, length: 50 })
|
||||||
|
timezone?: string | null; // e.g., "Asia/Riyadh", "America/New_York" - auto-detected from device
|
||||||
|
|
||||||
@Column('timestamp with time zone', { name: 'last_access_on', default: () => 'CURRENT_TIMESTAMP' })
|
@Column('timestamp with time zone', { name: 'last_access_on', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
lastAccessOn!: Date;
|
lastAccessOn!: Date;
|
||||||
|
|
||||||
|
|||||||
@ -61,12 +61,15 @@ export class User extends BaseEntity {
|
|||||||
@Column({ name: 'is_email_enabled', default: false })
|
@Column({ name: 'is_email_enabled', default: false })
|
||||||
isEmailEnabled!: boolean;
|
isEmailEnabled!: boolean;
|
||||||
|
|
||||||
@Column({ name: 'is_push_enabled', default: false })
|
@Column({ name: 'is_push_enabled', default: true })
|
||||||
isPushEnabled!: boolean;
|
isPushEnabled!: boolean;
|
||||||
|
|
||||||
@Column({ name: 'is_sms_enabled', default: false })
|
@Column({ name: 'is_sms_enabled', default: false })
|
||||||
isSmsEnabled!: boolean;
|
isSmsEnabled!: boolean;
|
||||||
|
|
||||||
|
@Column('varchar', { name: 'timezone', nullable: true, length: 50 })
|
||||||
|
timezone?: string | null; // User's preferred timezone for reports/statements (e.g., "Asia/Riyadh")
|
||||||
|
|
||||||
@Column('text', { nullable: true, array: true, name: 'roles' })
|
@Column('text', { nullable: true, array: true, name: 'roles' })
|
||||||
roles!: Roles[];
|
roles!: Roles[];
|
||||||
|
|
||||||
|
|||||||
@ -11,6 +11,10 @@ export class DeviceRepository {
|
|||||||
return this.deviceRepository.findOne({ where: { deviceId, userId } });
|
return this.deviceRepository.findOne({ where: { deviceId, userId } });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
findByDeviceId(deviceId: string) {
|
||||||
|
return this.deviceRepository.findOne({ where: { deviceId } });
|
||||||
|
}
|
||||||
|
|
||||||
createDevice(data: Partial<Device>) {
|
createDevice(data: Partial<Device>) {
|
||||||
return this.deviceRepository.save(data);
|
return this.deviceRepository.save(data);
|
||||||
}
|
}
|
||||||
@ -22,4 +26,8 @@ export class DeviceRepository {
|
|||||||
getTokens(userId: string) {
|
getTokens(userId: string) {
|
||||||
return this.deviceRepository.find({ where: { userId, fcmToken: Not(IsNull()) }, select: ['fcmToken'] });
|
return this.deviceRepository.find({ where: { userId, fcmToken: Not(IsNull()) }, select: ['fcmToken'] });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
findUserDevices(userId: string) {
|
||||||
|
return this.deviceRepository.find({ where: { userId } });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,6 +10,11 @@ export class DeviceService {
|
|||||||
return this.deviceRepository.findUserDeviceById(deviceId, userId);
|
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>) {
|
createDevice(data: Partial<Device>) {
|
||||||
this.logger.log(`Creating device with data ${JSON.stringify(data)}`);
|
this.logger.log(`Creating device with data ${JSON.stringify(data)}`);
|
||||||
return this.deviceRepository.createDevice(data);
|
return this.deviceRepository.createDevice(data);
|
||||||
@ -26,4 +31,9 @@ export class DeviceService {
|
|||||||
|
|
||||||
return devices.map((device) => device.fcmToken!);
|
return devices.map((device) => device.fcmToken!);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
findUserDevices(userId: string) {
|
||||||
|
this.logger.log(`Finding all devices for user ${userId}`);
|
||||||
|
return this.deviceRepository.findUserDevices(userId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,12 @@
|
|||||||
import { BadRequestException, forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
|
import { BadRequestException, forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import * as bcrypt from 'bcrypt';
|
import * as bcrypt from 'bcrypt';
|
||||||
import { FindOptionsWhere } from 'typeorm';
|
import { FindOptionsWhere } from 'typeorm';
|
||||||
import { Transactional } from 'typeorm-transactional';
|
import { Transactional } from 'typeorm-transactional';
|
||||||
import { CountryIso } from '~/common/enums';
|
import { CountryIso } from '~/common/enums';
|
||||||
|
import { NOTIFICATION_EVENTS } from '~/common/modules/notification/constants/event-names.constant';
|
||||||
|
import { IProfileUpdatedEvent } from '~/common/modules/notification/interfaces/notification-events.interface';
|
||||||
import { NotificationsService } from '~/common/modules/notification/services';
|
import { NotificationsService } from '~/common/modules/notification/services';
|
||||||
import { OtpScope, OtpType } from '~/common/modules/otp/enums';
|
import { OtpScope, OtpType } from '~/common/modules/otp/enums';
|
||||||
import { OtpService } from '~/common/modules/otp/services';
|
import { OtpService } from '~/common/modules/otp/services';
|
||||||
@ -28,6 +31,7 @@ export class UserService {
|
|||||||
private readonly documentService: DocumentService,
|
private readonly documentService: DocumentService,
|
||||||
private readonly otpService: OtpService,
|
private readonly otpService: OtpService,
|
||||||
private readonly ociService: OciService,
|
private readonly ociService: OciService,
|
||||||
|
private readonly eventEmitter: EventEmitter2,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async findUser(where: FindOptionsWhere<User> | FindOptionsWhere<User>[], includeSignedUrl = false) {
|
async findUser(where: FindOptionsWhere<User> | FindOptionsWhere<User>[], includeSignedUrl = false) {
|
||||||
@ -64,14 +68,12 @@ export class UserService {
|
|||||||
this.customerService.createGuardianCustomer(userId, {
|
this.customerService.createGuardianCustomer(userId, {
|
||||||
firstName: body.firstName,
|
firstName: body.firstName,
|
||||||
lastName: body.lastName,
|
lastName: body.lastName,
|
||||||
dateOfBirth: body.dateOfBirth,
|
|
||||||
countryOfResidence: body.countryOfResidence,
|
countryOfResidence: body.countryOfResidence,
|
||||||
}),
|
}),
|
||||||
this.userRepository.update(userId, {
|
this.userRepository.update(userId, {
|
||||||
isPhoneVerified: true,
|
isPhoneVerified: true,
|
||||||
password: hashedPassword,
|
password: hashedPassword,
|
||||||
salt,
|
salt,
|
||||||
...(body.email && { email: body.email }),
|
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@ -102,7 +104,6 @@ export class UserService {
|
|||||||
return this.userRepository.createUnverifiedUser({
|
return this.userRepository.createUnverifiedUser({
|
||||||
phoneNumber: body.phoneNumber,
|
phoneNumber: body.phoneNumber,
|
||||||
countryCode: body.countryCode,
|
countryCode: body.countryCode,
|
||||||
email: body.email,
|
|
||||||
firstName: body.firstName,
|
firstName: body.firstName,
|
||||||
lastName: body.lastName,
|
lastName: body.lastName,
|
||||||
roles: [Roles.GUARDIAN],
|
roles: [Roles.GUARDIAN],
|
||||||
@ -134,22 +135,55 @@ export class UserService {
|
|||||||
|
|
||||||
async updateNotificationSettings(userId: string, data: UpdateNotificationsSettingsRequestDto, deviceId?: string) {
|
async updateNotificationSettings(userId: string, data: UpdateNotificationsSettingsRequestDto, deviceId?: string) {
|
||||||
this.logger.log(`Updating notification settings for user ${userId} with data ${JSON.stringify(data)}`);
|
this.logger.log(`Updating notification settings for user ${userId} with data ${JSON.stringify(data)}`);
|
||||||
if (data.isPushEnabled && !data.fcmToken) {
|
|
||||||
|
const isPushEnabled = data.isPushEnabled ?? true;
|
||||||
|
|
||||||
|
if (isPushEnabled && !data.fcmToken) {
|
||||||
throw new BadRequestException('USER.FCM_TOKEN_REQUIRED');
|
throw new BadRequestException('USER.FCM_TOKEN_REQUIRED');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.isPushEnabled && !deviceId) {
|
if (isPushEnabled && data.fcmToken) {
|
||||||
throw new BadRequestException('DEVICE_ID_REQUIRED');
|
let targetDeviceId = deviceId;
|
||||||
}
|
|
||||||
|
|
||||||
if (data.isPushEnabled && deviceId && data.fcmToken) {
|
if (!targetDeviceId) {
|
||||||
await this.deviceService.updateDevice(deviceId, { fcmToken: data.fcmToken, userId });
|
const userDevices = await this.deviceService.findUserDevices(userId);
|
||||||
|
if (userDevices.length > 0) {
|
||||||
|
targetDeviceId = userDevices[0].deviceId;
|
||||||
|
this.logger.log(`No deviceId provided, using first device: ${targetDeviceId}`);
|
||||||
|
} else {
|
||||||
|
targetDeviceId = `device-${userId}-${Date.now()}`;
|
||||||
|
this.logger.log(`No device found, creating new device: ${targetDeviceId}`);
|
||||||
|
await this.deviceService.createDevice({
|
||||||
|
deviceId: targetDeviceId,
|
||||||
|
userId,
|
||||||
|
fcmToken: data.fcmToken,
|
||||||
|
lastAccessOn: new Date(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetDeviceId) {
|
||||||
|
const existingDevice = await this.deviceService.findUserDeviceById(targetDeviceId, userId);
|
||||||
|
if (existingDevice) {
|
||||||
|
await this.deviceService.updateDevice(targetDeviceId, { fcmToken: data.fcmToken, userId });
|
||||||
|
} else {
|
||||||
|
const anyDevice = await this.deviceService.findByDeviceId(targetDeviceId);
|
||||||
|
if (anyDevice) {
|
||||||
|
await this.deviceService.updateDevice(targetDeviceId, { fcmToken: data.fcmToken, userId });
|
||||||
|
} else {
|
||||||
|
await this.deviceService.createDevice({
|
||||||
|
deviceId: targetDeviceId,
|
||||||
|
userId,
|
||||||
|
fcmToken: data.fcmToken,
|
||||||
|
lastAccessOn: new Date(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.userRepository.update(userId, {
|
await this.userRepository.update(userId, {
|
||||||
isPushEnabled: data.isPushEnabled,
|
isPushEnabled: isPushEnabled,
|
||||||
isEmailEnabled: data.isEmailEnabled,
|
|
||||||
isSmsEnabled: data.isSmsEnabled,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -219,6 +253,19 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
await this.customerService.updateCustomer(userId, customerData);
|
await this.customerService.updateCustomer(userId, customerData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const updatedUser = await this.findUserOrThrow({ id: userId });
|
||||||
|
const updatedFields = Object.keys(data).filter(key => (data as any)[key] !== undefined);
|
||||||
|
|
||||||
|
if (updatedFields.length > 0) {
|
||||||
|
const event: IProfileUpdatedEvent = {
|
||||||
|
user: updatedUser,
|
||||||
|
updatedFields,
|
||||||
|
timestamp: new Date(),
|
||||||
|
};
|
||||||
|
this.eventEmitter.emit(NOTIFICATION_EVENTS.PROFILE_UPDATED, event);
|
||||||
|
this.logger.log(`Emitted PROFILE_UPDATED event for user ${userId}, updated fields: ${updatedFields.join(', ')}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateUserEmail(userId: string, email: string) {
|
async updateUserEmail(userId: string, email: string) {
|
||||||
@ -249,6 +296,15 @@ export class UserService {
|
|||||||
throw new BadRequestException('USER.NOT_FOUND');
|
throw new BadRequestException('USER.NOT_FOUND');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const updatedUser = await this.findUserOrThrow({ id: userId });
|
||||||
|
const event: IProfileUpdatedEvent = {
|
||||||
|
user: updatedUser,
|
||||||
|
updatedFields: ['email'],
|
||||||
|
timestamp: new Date(),
|
||||||
|
};
|
||||||
|
this.eventEmitter.emit(NOTIFICATION_EVENTS.PROFILE_UPDATED, event);
|
||||||
|
this.logger.log(`Emitted PROFILE_UPDATED event for user ${userId}, updated field: email`);
|
||||||
|
|
||||||
return this.otpService.generateAndSendOtp({
|
return this.otpService.generateAndSendOtp({
|
||||||
userId,
|
userId,
|
||||||
recipient: email,
|
recipient: email,
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
|
||||||
import { INestApplication } from '@nestjs/common';
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import request from 'supertest';
|
import request from 'supertest';
|
||||||
import { AppModule } from './../src/app.module';
|
import { AppModule } from './../src/app.module';
|
||||||
|
|
||||||
@ -18,4 +18,6 @@ describe('AppController (e2e)', () => {
|
|||||||
it('/ (GET)', () => {
|
it('/ (GET)', () => {
|
||||||
return request(app.getHttpServer()).get('/').expect(200).expect('Hello World!');
|
return request(app.getHttpServer()).get('/').expect(200).expect('Hello World!');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user