Compare commits

..

14 Commits

81 changed files with 1652 additions and 1090 deletions

1
.gitignore vendored
View File

@ -53,3 +53,4 @@ pids
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
zod-certs

View File

@ -10,8 +10,7 @@
"include": "config",
"exclude": "**/*.md"
},
{ "include": "common/modules/**/templates/*", "watchAssets": true }
,
{ "include": "common/modules/**/templates/**/*", "watchAssets": true },
"i18n",
"files"
]

35
package-lock.json generated
View File

@ -36,7 +36,7 @@
"firebase-admin": "^13.0.2",
"google-libphonenumber": "^3.2.39",
"handlebars": "^4.7.8",
"ioredis": "^5.4.1",
"handlebars-layouts": "^3.1.4",
"jwk-to-pem": "^2.0.7",
"lodash": "^4.17.21",
"moment": "^2.30.1",
@ -1187,7 +1187,9 @@
},
"node_modules/@ioredis/commands": {
"version": "1.2.0",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
@ -5239,6 +5241,8 @@
"node_modules/denque": {
"version": "2.1.0",
"license": "Apache-2.0",
"optional": true,
"peer": true,
"engines": {
"node": ">=0.10"
}
@ -6980,6 +6984,15 @@
"uglify-js": "^3.1.4"
}
},
"node_modules/handlebars-layouts": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/handlebars-layouts/-/handlebars-layouts-3.1.4.tgz",
"integrity": "sha512-2llBmvnj8ueOfxNHdRzJOcgalzZjYVd9+WAl93kPYmlX4WGx7FTHTzNxhK+i9YKY2OSjzfehgpLiIwP/OJr6tw==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/handlebars/node_modules/source-map": {
"version": "0.6.1",
"license": "BSD-3-Clause",
@ -7381,6 +7394,8 @@
"node_modules/ioredis": {
"version": "5.4.1",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"@ioredis/commands": "^1.1.1",
"cluster-key-slot": "^1.1.0",
@ -9105,7 +9120,9 @@
},
"node_modules/lodash.defaults": {
"version": "4.2.0",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/lodash.includes": {
"version": "4.3.0",
@ -9113,7 +9130,9 @@
},
"node_modules/lodash.isarguments": {
"version": "3.1.0",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/lodash.isboolean": {
"version": "3.0.3",
@ -15708,6 +15727,8 @@
"node_modules/redis-errors": {
"version": "1.2.0",
"license": "MIT",
"optional": true,
"peer": true,
"engines": {
"node": ">=4"
}
@ -15715,6 +15736,8 @@
"node_modules/redis-parser": {
"version": "3.0.0",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"redis-errors": "^1.0.0"
},
@ -16499,7 +16522,9 @@
},
"node_modules/standard-as-callback": {
"version": "2.1.0",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/statuses": {
"version": "2.0.1",

View File

@ -54,7 +54,7 @@
"firebase-admin": "^13.0.2",
"google-libphonenumber": "^3.2.39",
"handlebars": "^4.7.8",
"ioredis": "^5.4.1",
"handlebars-layouts": "^3.1.4",
"jwk-to-pem": "^2.0.7",
"lodash": "^4.17.21",
"moment": "^2.30.1",

View File

@ -1,23 +1,24 @@
import { Body, Controller, Headers, HttpCode, HttpStatus, Post, Req, UseGuards } from '@nestjs/common';
import { Body, Controller, HttpCode, HttpStatus, Post, Req, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import { DEVICE_ID_HEADER } from '~/common/constants';
import { AuthenticatedUser, Public } from '~/common/decorators';
import { AccessTokenGuard } from '~/common/guards';
import { ApiLangRequestHeader } from '~/core/decorators';
import { ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
import { ResponseFactory } from '~/core/utils';
import {
AppleLoginRequestDto,
CreateUnverifiedUserRequestDto,
DisableBiometricRequestDto,
EnableBiometricRequestDto,
ForgetPasswordRequestDto,
LoginRequestDto,
GoogleLoginRequestDto,
RefreshTokenRequestDto,
SendForgetPasswordOtpRequestDto,
SendLoginOtpRequestDto,
SetEmailRequestDto,
setJuniorPasswordRequestDto,
SetPasscodeRequestDto,
VerifyOtpRequestDto,
VerifyLoginOtpRequestDto,
VerifyUserRequestDto,
} from '../dtos/request';
import { SendForgetPasswordOtpResponseDto, SendRegisterOtpResponseDto } from '../dtos/response';
@ -43,6 +44,36 @@ export class AuthController {
return ResponseFactory.data(new LoginResponseDto(res, user));
}
@Post('login/otp')
@HttpCode(HttpStatus.NO_CONTENT)
async sendLoginOtp(@Body() data: SendLoginOtpRequestDto) {
return this.authService.sendLoginOtp(data);
}
@Post('login/verify')
@HttpCode(HttpStatus.OK)
@ApiDataResponse(LoginResponseDto)
async verifyLoginOtp(@Body() data: VerifyLoginOtpRequestDto) {
const [token, user] = await this.authService.verifyLoginOtp(data);
return ResponseFactory.data(new LoginResponseDto(token, user));
}
@Post('login/google')
@HttpCode(HttpStatus.OK)
@ApiDataResponse(LoginResponseDto)
async loginWithGoogle(@Body() data: GoogleLoginRequestDto) {
const [token, user] = await this.authService.loginWithGoogle(data);
return ResponseFactory.data(new LoginResponseDto(token, user));
}
@Post('login/apple')
@HttpCode(HttpStatus.OK)
@ApiDataResponse(LoginResponseDto)
async loginWithApple(@Body() data: AppleLoginRequestDto) {
const [token, user] = await this.authService.loginWithApple(data);
return ResponseFactory.data(new LoginResponseDto(token, user));
}
@Post('register/set-email')
@HttpCode(HttpStatus.NO_CONTENT)
@UseGuards(AccessTokenGuard)
@ -57,22 +88,22 @@ export class AuthController {
await this.authService.setPasscode(sub, passcode);
}
@Post('register/set-phone/otp')
@UseGuards(AccessTokenGuard)
async setPhoneNumber(
@AuthenticatedUser() { sub }: IJwtPayload,
@Body() setPhoneNumberDto: CreateUnverifiedUserRequestDto,
) {
const phoneNumber = await this.authService.setPhoneNumber(sub, setPhoneNumberDto);
return ResponseFactory.data(new SendRegisterOtpResponseDto(phoneNumber));
}
// @Post('register/set-phone/otp')
// @UseGuards(AccessTokenGuard)
// async setPhoneNumber(
// @AuthenticatedUser() { sub }: IJwtPayload,
// @Body() setPhoneNumberDto: CreateUnverifiedUserRequestDto,
// ) {
// const phoneNumber = await this.authService.setPhoneNumber(sub, setPhoneNumberDto);
// return ResponseFactory.data(new SendRegisterOtpResponseDto(phoneNumber));
// }
@Post('register/set-phone/verify')
@HttpCode(HttpStatus.NO_CONTENT)
@UseGuards(AccessTokenGuard)
async verifyPhoneNumber(@AuthenticatedUser() { sub }: IJwtPayload, @Body() { otp }: VerifyOtpRequestDto) {
await this.authService.verifyPhoneNumber(sub, otp);
}
// @Post('register/set-phone/verify')
// @HttpCode(HttpStatus.NO_CONTENT)
// @UseGuards(AccessTokenGuard)
// async verifyPhoneNumber(@AuthenticatedUser() { sub }: IJwtPayload, @Body() { otp }: VerifyOtpRequestDto) {
// await this.authService.verifyPhoneNumber(sub, otp);
// }
@Post('biometric/enable')
@HttpCode(HttpStatus.NO_CONTENT)
@ -114,12 +145,6 @@ export class AuthController {
return ResponseFactory.data(new LoginResponseDto(res, user));
}
@Post('login')
async login(@Body() loginDto: LoginRequestDto, @Headers(DEVICE_ID_HEADER) deviceId: string) {
const [res, user] = await this.authService.login(loginDto, deviceId);
return ResponseFactory.data(new LoginResponseDto(res, user));
}
@Post('logout')
@HttpCode(HttpStatus.NO_CONTENT)
@UseGuards(AccessTokenGuard)

View File

@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
export class AppleAdditionalData {
@ApiProperty({ example: 'Ahmad' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.firstName' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.firstName' }) })
firstName!: string;
@ApiProperty({ example: 'Khan' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.lastName' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.lastName' }) })
lastName!: string;
}

View File

@ -0,0 +1,21 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsNotEmpty, IsOptional, IsString, ValidateNested } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { AppleAdditionalData } from './apple-additional-data.request.dto';
export class AppleLoginRequestDto {
@ApiProperty({ example: 'apple_token' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.appleToken' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'auth.appleToken' }) })
appleToken!: string;
@ApiProperty({ type: AppleAdditionalData })
@ValidateNested({
each: true,
message: i18n('validation.ValidateNested', { path: 'general', property: 'auth.apple.additionalData' }),
})
@IsOptional()
@Type(() => AppleAdditionalData)
additionalData?: AppleAdditionalData;
}

View File

@ -1,19 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { Matches } from 'class-validator';
import { IsEmail } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { COUNTRY_CODE_REGEX } from '~/auth/constants';
import { IsValidPhoneNumber } from '~/core/decorators/validations';
export class CreateUnverifiedUserRequestDto {
@ApiProperty({ example: '+962' })
@Matches(COUNTRY_CODE_REGEX, {
message: i18n('validation.Matches', { path: 'general', property: 'auth.countryCode' }),
})
countryCode: string = '+966';
@ApiProperty({ example: '787259134' })
@IsValidPhoneNumber({
message: i18n('validation.IsValidPhoneNumber', { path: 'general', property: 'auth.phoneNumber' }),
})
phoneNumber!: string;
@ApiProperty({ example: 'test@test.com' })
@IsEmail(
{},
{
message: i18n('validation.IsEmail', { path: 'general', property: 'auth.email' }),
},
)
email!: string;
}

View File

@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
export class GoogleLoginRequestDto {
@ApiProperty({ example: 'google_token' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'auth.googleToken' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'auth.googleToken' }) })
googleToken!: string;
}

View File

@ -1,12 +1,16 @@
export * from './apple-login.request.dto';
export * from './create-unverified-user.request.dto';
export * from './disable-biometric.request.dto';
export * from './enable-biometric.request.dto';
export * from './forget-password.request.dto';
export * from './google-login.request.dto';
export * from './login.request.dto';
export * from './refresh-token.request.dto';
export * from './send-forget-password-otp.request.dto';
export * from './send-login-otp.request.dto';
export * from './set-email.request.dto';
export * from './set-junior-password.request.dto';
export * from './set-passcode.request.dto';
export * from './verify-login-otp.request.dto';
export * from './verify-otp.request.dto';
export * from './verify-user.request.dto';

View File

@ -3,7 +3,7 @@ import { IsEmail, IsEnum, IsNotEmpty, IsOptional, IsString, ValidateIf } from 'c
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { GrantType } from '~/auth/enums';
export class LoginRequestDto {
@ApiProperty({ example: GrantType.PASSWORD })
@ApiProperty({ example: GrantType.APPLE })
@IsEnum(GrantType, { message: i18n('validation.IsEnum', { path: 'general', property: 'auth.grantType' }) })
grantType!: GrantType;

View File

@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
export class SendLoginOtpRequestDto {
@ApiProperty({ example: 'test@test.com' })
@IsEmail({}, { message: i18n('validation.IsEmail', { path: 'general', property: 'auth.email' }) })
email!: string;
}

View File

@ -0,0 +1,20 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNumberString, MaxLength, MinLength } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { DEFAULT_OTP_LENGTH } from '~/common/modules/otp/constants';
import { SendLoginOtpRequestDto } from './send-login-otp.request.dto';
export class VerifyLoginOtpRequestDto extends SendLoginOtpRequestDto {
@ApiProperty({ example: '111111' })
@IsNumberString(
{ no_symbols: true },
{ message: i18n('validation.IsNumberString', { path: 'general', property: 'auth.otp' }) },
)
@MaxLength(DEFAULT_OTP_LENGTH, {
message: i18n('validation.MaxLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
})
@MinLength(DEFAULT_OTP_LENGTH, {
message: i18n('validation.MinLength', { path: 'general', property: 'auth.otp', length: DEFAULT_OTP_LENGTH }),
})
otp!: string;
}

View File

@ -1,10 +1,43 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNumberString, MaxLength, MinLength } from 'class-validator';
import { ApiProperty, PickType } from '@nestjs/swagger';
import {
IsDateString,
IsEnum,
IsNotEmpty,
IsNumberString,
IsOptional,
IsString,
MaxLength,
MinLength,
} from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { CountryIso } from '~/common/enums';
import { DEFAULT_OTP_LENGTH } from '~/common/modules/otp/constants';
import { IsAbove18 } from '~/core/decorators/validations';
import { CreateUnverifiedUserRequestDto } from './create-unverified-user.request.dto';
export class VerifyUserRequestDto extends CreateUnverifiedUserRequestDto {
export class VerifyUserRequestDto extends PickType(CreateUnverifiedUserRequestDto, ['email']) {
@ApiProperty({ example: 'John' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.firstName' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.firstName' }) })
firstName!: string;
@ApiProperty({ example: 'Doe' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.lastName' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.lastName' }) })
lastName!: string;
@ApiProperty({ example: '2021-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' })
@IsEnum(CountryIso, {
message: i18n('validation.IsEnum', { path: 'general', property: 'customer.countryOfResidence' }),
})
@IsOptional()
countryOfResidence: CountryIso = CountryIso.SAUDI_ARABIA;
@ApiProperty({ example: '111111' })
@IsNumberString(
{ no_symbols: true },

View File

@ -2,9 +2,9 @@ import { ApiProperty } from '@nestjs/swagger';
export class SendRegisterOtpResponseDto {
@ApiProperty()
phoneNumber!: string;
email!: string;
constructor(phoneNumber: string) {
this.phoneNumber = phoneNumber;
constructor(email: string) {
this.email = email;
}
}

View File

@ -12,17 +12,21 @@ import { DeviceService, UserService, UserTokenService } from '~/user/services';
import { User } from '../../user/entities';
import { PASSCODE_REGEX } from '../constants';
import {
AppleLoginRequestDto,
CreateUnverifiedUserRequestDto,
DisableBiometricRequestDto,
EnableBiometricRequestDto,
ForgetPasswordRequestDto,
GoogleLoginRequestDto,
LoginRequestDto,
SendForgetPasswordOtpRequestDto,
SendLoginOtpRequestDto,
SetEmailRequestDto,
setJuniorPasswordRequestDto,
VerifyLoginOtpRequestDto,
VerifyUserRequestDto,
} from '../dtos/request';
import { GrantType, Roles } from '../enums';
import { Roles } from '../enums';
import { IJwtPayload, ILoginResponse } from '../interfaces';
import { removePadding, verifySignature } from '../utils';
import { Oauth2Service } from './oauth2.service';
@ -43,62 +47,45 @@ export class AuthService {
private readonly cacheService: CacheService,
private readonly oauth2Service: Oauth2Service,
) {}
async sendRegisterOtp({ phoneNumber, countryCode }: CreateUnverifiedUserRequestDto) {
this.logger.log(`Sending OTP to ${countryCode + phoneNumber}`);
const user = await this.userService.findOrCreateUser({ phoneNumber, countryCode });
async sendRegisterOtp(body: CreateUnverifiedUserRequestDto) {
this.logger.log(`Sending OTP to ${body.email}`);
const user = await this.userService.findOrCreateUser(body);
return this.otpService.generateAndSendOtp({
userId: user.id,
recipient: user.countryCode + user.phoneNumber,
scope: OtpScope.VERIFY_PHONE,
otpType: OtpType.SMS,
recipient: user.email,
scope: OtpScope.VERIFY_EMAIL,
otpType: OtpType.EMAIL,
});
}
async verifyUser(verifyUserDto: VerifyUserRequestDto): Promise<[ILoginResponse, User]> {
this.logger.log(`Verifying user with phone number ${verifyUserDto.countryCode + verifyUserDto.phoneNumber}`);
const user = await this.userService.findUserOrThrow({ phoneNumber: verifyUserDto.phoneNumber });
this.logger.log(`Verifying user with email ${verifyUserDto.email}`);
const user = await this.userService.findUserOrThrow({ email: verifyUserDto.email });
if (user.isProfileCompleted) {
this.logger.error(
`User with phone number ${verifyUserDto.countryCode + verifyUserDto.phoneNumber} already verified`,
);
throw new BadRequestException('USER.PHONE_ALREADY_VERIFIED');
if (user.isEmailVerified) {
this.logger.error(`User with email ${verifyUserDto.email} already verified`);
throw new BadRequestException('USER.EMAIL_ALREADY_VERIFIED');
}
const isOtpValid = await this.otpService.verifyOtp({
userId: user.id,
scope: OtpScope.VERIFY_PHONE,
otpType: OtpType.SMS,
scope: OtpScope.VERIFY_EMAIL,
otpType: OtpType.EMAIL,
value: verifyUserDto.otp,
});
if (!isOtpValid) {
this.logger.error(
`Invalid OTP for user with phone number ${verifyUserDto.countryCode + verifyUserDto.phoneNumber}`,
);
this.logger.error(`Invalid OTP for user with email ${verifyUserDto.email}`);
throw new BadRequestException('OTP.INVALID_OTP');
}
if (user.isPhoneVerified) {
this.logger.log(
`User with phone number ${
verifyUserDto.countryCode + verifyUserDto.phoneNumber
} already verified but did not complete registration process`,
);
const tokens = await this.generateAuthToken(user);
return [tokens, user];
}
await this.userService.verifyPhoneNumber(user.id);
await this.userService.verifyUser(user.id, verifyUserDto);
await user.reload();
const tokens = await this.generateAuthToken(user);
this.logger.log(
`User with phone number ${verifyUserDto.countryCode + verifyUserDto.phoneNumber} verified successfully`,
);
this.logger.log(`User with email ${verifyUserDto.email} verified successfully`);
return [tokens, user];
}
@ -136,46 +123,46 @@ export class AuthService {
this.logger.log(`Passcode set successfully for user with id ${userId}`);
}
async setPhoneNumber(userId: string, { phoneNumber, countryCode }: CreateUnverifiedUserRequestDto) {
const user = await this.userService.findUserOrThrow({ id: userId });
// async setPhoneNumber(userId: string, { phoneNumber, countryCode }: CreateUnverifiedUserRequestDto) {
// const user = await this.userService.findUserOrThrow({ id: userId });
if (user.phoneNumber || user.countryCode) {
this.logger.error(`Phone number already set for user with id ${userId}`);
throw new BadRequestException('USER.PHONE_NUMBER_ALREADY_SET');
}
// if (user.phoneNumber || user.countryCode) {
// this.logger.error(`Phone number already set for user with id ${userId}`);
// throw new BadRequestException('USER.PHONE_NUMBER_ALREADY_SET');
// }
const existingUser = await this.userService.findUser({ phoneNumber, countryCode });
// const existingUser = await this.userService.findUser({ phoneNumber, countryCode });
if (existingUser) {
this.logger.error(`Phone number ${countryCode + phoneNumber} already taken`);
throw new BadRequestException('USER.PHONE_NUMBER_ALREADY_TAKEN');
}
// if (existingUser) {
// this.logger.error(`Phone number ${countryCode + phoneNumber} already taken`);
// throw new BadRequestException('USER.PHONE_NUMBER_ALREADY_TAKEN');
// }
await this.userService.setPhoneNumber(userId, phoneNumber, countryCode);
// await this.userService.setPhoneNumber(userId, phoneNumber, countryCode);
return this.otpService.generateAndSendOtp({
userId,
recipient: countryCode + phoneNumber,
scope: OtpScope.VERIFY_PHONE,
otpType: OtpType.SMS,
});
}
// return this.otpService.generateAndSendOtp({
// userId,
// recipient: countryCode + phoneNumber,
// scope: OtpScope.VERIFY_PHONE,
// otpType: OtpType.SMS,
// });
// }
async verifyPhoneNumber(userId: string, otp: string) {
const isOtpValid = await this.otpService.verifyOtp({
otpType: OtpType.SMS,
scope: OtpScope.VERIFY_PHONE,
userId,
value: otp,
});
// async verifyPhoneNumber(userId: string, otp: string) {
// const isOtpValid = await this.otpService.verifyOtp({
// otpType: OtpType.SMS,
// scope: OtpScope.VERIFY_PHONE,
// userId,
// value: otp,
// });
if (!isOtpValid) {
this.logger.error(`Invalid OTP for user with id ${userId}`);
throw new BadRequestException('OTP.INVALID_OTP');
}
// if (!isOtpValid) {
// this.logger.error(`Invalid OTP for user with id ${userId}`);
// throw new BadRequestException('OTP.INVALID_OTP');
// }
return this.userService.verifyPhoneNumber(userId);
}
// return this.userService.verifyPhoneNumber(userId);
// }
async enableBiometric(userId: string, { deviceId, publicKey }: EnableBiometricRequestDto) {
this.logger.log(`Enabling biometric for user with id ${userId}`);
@ -258,41 +245,6 @@ export class AuthService {
this.logger.log(`Passcode updated successfully for user with email ${email}`);
}
async login(loginDto: LoginRequestDto, deviceId: string): Promise<[ILoginResponse, User]> {
let user: User;
let tokens: ILoginResponse;
if (loginDto.grantType === GrantType.GOOGLE) {
this.logger.log(`Logging in user with email ${loginDto.email} using google`);
[tokens, user] = await this.loginWithGoogle(loginDto);
}
if (loginDto.grantType === GrantType.APPLE) {
this.logger.log(`Logging in user with email ${loginDto.email} using apple`);
[tokens, user] = await this.loginWithApple(loginDto);
}
if (loginDto.grantType === GrantType.PASSWORD) {
this.logger.log(`Logging in user with email ${loginDto.email} using password`);
[tokens, user] = await this.loginWithPassword(loginDto);
}
if (loginDto.grantType === GrantType.BIOMETRIC) {
this.logger.log(`Logging in user with email ${loginDto.email} using biometric`);
[tokens, user] = await this.loginWithBiometric(loginDto, deviceId);
}
await this.deviceService.updateDevice(deviceId, {
lastAccessOn: new Date(),
fcmToken: loginDto.fcmToken,
userId: user!.id,
});
this.logger.log(`User with email ${loginDto.email} logged in successfully`);
return [tokens!, user!];
}
async setJuniorPasscode(body: setJuniorPasswordRequestDto) {
this.logger.log(`Setting passcode for junior with qrToken ${body.qrToken}`);
const juniorId = await this.userTokenService.validateToken(body.qrToken, UserType.JUNIOR);
@ -305,6 +257,14 @@ export class AuthService {
async refreshToken(refreshToken: string): Promise<[ILoginResponse, User]> {
this.logger.log('Refreshing token');
const isBlackListed = await this.cacheService.get(refreshToken);
if (isBlackListed) {
this.logger.error('Refresh token is blacklisted');
throw new BadRequestException('AUTH.INVALID_REFRESH_TOKEN');
}
try {
const isValid = await this.jwtService.verifyAsync<IJwtPayload>(refreshToken, {
secret: this.configService.getOrThrow('JWT_REFRESH_TOKEN_SECRET'),
@ -316,6 +276,12 @@ export class AuthService {
const tokens = await this.generateAuthToken(user);
this.logger.log(`Blacklisting old tokens for user with id ${isValid.sub}`);
const refreshTokenExpiry = this.jwtService.decode(refreshToken).exp - Date.now() / ONE_THOUSAND;
await this.cacheService.set(refreshToken, 'BLACKLISTED', refreshTokenExpiry);
this.logger.log(`Token refreshed successfully for user with id ${isValid.sub}`);
return [tokens, user];
@ -325,11 +291,45 @@ export class AuthService {
}
}
async sendLoginOtp({ email }: SendLoginOtpRequestDto) {
const user = await this.userService.findUserOrThrow({ email });
this.logger.log(`Sending login OTP to ${email}`);
return this.otpService.generateAndSendOtp({
recipient: email,
scope: OtpScope.LOGIN,
otpType: OtpType.EMAIL,
userId: user.id,
});
}
async verifyLoginOtp({ email, otp }: VerifyLoginOtpRequestDto): Promise<[ILoginResponse, User]> {
const user = await this.userService.findUserOrThrow({ email });
this.logger.log(`Verifying login OTP for ${email}`);
const isOtpValid = await this.otpService.verifyOtp({
otpType: OtpType.EMAIL,
scope: OtpScope.LOGIN,
userId: user.id,
value: otp,
});
if (!isOtpValid) {
this.logger.error(`Invalid OTP for user with email ${email}`);
throw new BadRequestException('OTP.INVALID_OTP');
}
this.logger.log(`Login OTP verified successfully for ${email}`);
const token = await this.generateAuthToken(user);
return [token, user];
}
logout(req: Request) {
this.logger.log('Logging out');
const accessToken = req.headers.authorization?.split(' ')[1] as string;
const expiryInTtl = this.jwtService.decode(accessToken).exp - Date.now() / ONE_THOUSAND;
return this.cacheService.set(accessToken, 'LOGOUT', expiryInTtl);
return this.cacheService.set(accessToken, 'BLACKLISTED', expiryInTtl);
}
private async loginWithPassword(loginDto: LoginRequestDto): Promise<[ILoginResponse, User]> {
@ -382,65 +382,96 @@ export class AuthService {
return [tokens, user];
}
private async loginWithGoogle(loginDto: LoginRequestDto): Promise<[ILoginResponse, User]> {
const { email, sub } = await this.oauth2Service.verifyGoogleToken(loginDto.googleToken);
const [existingUser, isJunior] = await Promise.all([
async loginWithGoogle(loginDto: GoogleLoginRequestDto): Promise<[ILoginResponse, User]> {
const {
email,
sub,
given_name: firstName,
family_name: lastName,
} = await this.oauth2Service.verifyGoogleToken(loginDto.googleToken);
const [existingUser, isJunior, existingUserWithEmail] = await Promise.all([
this.userService.findUser({ googleId: sub }),
this.userService.findUser({ email, roles: ArrayContains([Roles.JUNIOR]) }),
this.userService.findUser({ email }),
]);
if (isJunior && email) {
if (isJunior) {
this.logger.error(`User with email ${email} is an already registered junior`);
throw new BadRequestException('USER.JUNIOR_UPGRADE_NOT_SUPPORTED_YET');
}
if (!existingUser) {
this.logger.debug(`User with google id ${sub} not found, creating new user`);
const user = await this.userService.createGoogleUser(sub, email);
if (!existingUser && existingUserWithEmail) {
this.logger.error(`User with email ${email} already exists adding google id to existing user`);
await this.userService.updateUser(existingUserWithEmail.id, { googleId: sub });
const tokens = await this.generateAuthToken(existingUserWithEmail);
return [tokens, existingUserWithEmail];
}
if (!existingUser && !existingUserWithEmail) {
this.logger.debug(`User with google id ${sub} or email ${email} not found, creating new user`);
const user = await this.userService.createGoogleUser(sub, email, firstName, lastName);
const tokens = await this.generateAuthToken(user);
return [tokens, user];
}
const tokens = await this.generateAuthToken(existingUser);
const tokens = await this.generateAuthToken(existingUser!);
return [tokens, existingUser];
return [tokens, existingUser!];
}
private async loginWithApple(loginDto: LoginRequestDto): Promise<[ILoginResponse, User]> {
async loginWithApple(loginDto: AppleLoginRequestDto): Promise<[ILoginResponse, User]> {
const { sub, email } = await this.oauth2Service.verifyAppleToken(loginDto.appleToken);
const [existingUser, isJunior] = await Promise.all([
const [existingUserWithSub, isJunior] = await Promise.all([
this.userService.findUser({ appleId: sub }),
this.userService.findUser({ email, roles: ArrayContains([Roles.JUNIOR]) }),
]);
if (isJunior && email) {
this.logger.error(`User with email ${email} is an already registered junior`);
if (isJunior) {
this.logger.error(`User with apple id ${sub} is an already registered junior`);
throw new BadRequestException('USER.JUNIOR_UPGRADE_NOT_SUPPORTED_YET');
}
if (!existingUser) {
if (email) {
const existingUserWithEmail = await this.userService.findUser({ email });
if (existingUserWithEmail && !existingUserWithSub) {
{
this.logger.error(`User with email ${email} already exists adding apple id to existing user`);
await this.userService.updateUser(existingUserWithEmail.id, { appleId: sub });
const tokens = await this.generateAuthToken(existingUserWithEmail);
return [tokens, existingUserWithEmail];
}
}
}
if (!existingUserWithSub) {
// Apple only provides email if user authorized zod for the first time
if (!email) {
if (!email || !loginDto.additionalData) {
this.logger.error(`User authorized zod before but his email is not stored in the database`);
throw new BadRequestException('AUTH.APPLE_RE-CONSENT_REQUIRED');
}
this.logger.debug(`User with apple id ${sub} not found, creating new user`);
const user = await this.userService.createAppleUser(sub, email);
const user = await this.userService.createAppleUser(
sub,
email,
loginDto.additionalData.firstName,
loginDto.additionalData.lastName,
);
const tokens = await this.generateAuthToken(user);
return [tokens, user];
}
const tokens = await this.generateAuthToken(existingUser);
const tokens = await this.generateAuthToken(existingUserWithSub);
this.logger.log(`User with apple id ${sub} logged in successfully`);
return [tokens, existingUser];
return [tokens, existingUserWithSub];
}
private async generateAuthToken(user: User) {
@ -478,4 +509,6 @@ export class AuthService {
throw new BadRequestException('AUTH.INVALID_PASSCODE');
}
}
private validateGoogleToken(googleToken: string) {}
}

View File

@ -49,7 +49,7 @@ export class Oauth2Service {
const payload = this.jwtService.verify(appleToken, {
publicKey,
algorithms: ['RS256'],
audience: this.configService.getOrThrow('APPLE_CLIENT_ID'),
audience: this.configService.getOrThrow('APPLE_CLIENT_ID').split(','),
issuer: this.appleIssuer,
});

View File

@ -1,12 +1,13 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserService } from '~/user/services';
import { IJwtPayload } from '../interfaces';
@Injectable()
export class AccessTokenStrategy extends PassportStrategy(Strategy, 'access-token') {
constructor(configService: ConfigService) {
constructor(configService: ConfigService, private userService: UserService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
@ -14,7 +15,13 @@ export class AccessTokenStrategy extends PassportStrategy(Strategy, 'access-toke
});
}
validate(payload: IJwtPayload) {
async validate(payload: IJwtPayload) {
const user = await this.userService.findUser({ id: payload.sub });
if (!user) {
throw new UnauthorizedException();
}
return payload;
}
}

View File

@ -0,0 +1,253 @@
import { CountryIso } from '../enums';
export const CountriesNumericISO: Record<CountryIso, string> = {
[CountryIso.ARUBA]: '533',
[CountryIso.AFGHANISTAN]: '004',
[CountryIso.ANGOLA]: '024',
[CountryIso.ANGUILLA]: '660',
[CountryIso.ALAND_ISLANDS]: '248',
[CountryIso.ALBANIA]: '008',
[CountryIso.ANDORRA]: '020',
[CountryIso.UNITED_ARAB_EMIRATES]: '784',
[CountryIso.ARGENTINA]: '032',
[CountryIso.ARMENIA]: '051',
[CountryIso.AMERICAN_SAMOA]: '016',
[CountryIso.ANTARCTICA]: '010',
[CountryIso.FRENCH_SOUTHERN_TERRITORIES]: '260',
[CountryIso.ANTIGUA_AND_BARBUDA]: '028',
[CountryIso.AUSTRALIA]: '036',
[CountryIso.AUSTRIA]: '040',
[CountryIso.AZERBAIJAN]: '031',
[CountryIso.BURUNDI]: '108',
[CountryIso.BELGIUM]: '056',
[CountryIso.BENIN]: '204',
[CountryIso.BONAIRE_SINT_EUSTATIUS_AND_SABA]: '535',
[CountryIso.BURKINA_FASO]: '854',
[CountryIso.BANGLADESH]: '050',
[CountryIso.BULGARIA]: '100',
[CountryIso.BAHRAIN]: '048',
[CountryIso.BAHAMAS]: '044',
[CountryIso.BOSNIA_AND_HERZEGOVINA]: '070',
[CountryIso.SAINT_BARTHÉLEMY]: '652',
[CountryIso.BELARUS]: '112',
[CountryIso.BELIZE]: '084',
[CountryIso.BERMUDA]: '060',
[CountryIso.BOLIVIA_PLURINATIONAL_STATE_OF]: '068',
[CountryIso.BRAZIL]: '076',
[CountryIso.BARBADOS]: '052',
[CountryIso.BRUNEI_DARUSSALAM]: '096',
[CountryIso.BHUTAN]: '064',
[CountryIso.BOUVET_ISLAND]: '074',
[CountryIso.BOTSWANA]: '072',
[CountryIso.CENTRAL_AFRICAN_REPUBLIC]: '140',
[CountryIso.CANADA]: '124',
[CountryIso.COCOS_KEELING_ISLANDS]: '166',
[CountryIso.SWITZERLAND]: '756',
[CountryIso.CHILE]: '152',
[CountryIso.CHINA]: '156',
[CountryIso.COTE_DIVOIRE]: '384',
[CountryIso.CAMEROON]: '120',
[CountryIso.CONGO_THE_DEMOCRATIC_REPUBLIC_OF_THE]: '180',
[CountryIso.CONGO]: '178',
[CountryIso.COOK_ISLANDS]: '184',
[CountryIso.COLOMBIA]: '170',
[CountryIso.COMOROS]: '174',
[CountryIso.CABO_VERDE]: '132',
[CountryIso.COSTA_RICA]: '188',
[CountryIso.CUBA]: '192',
[CountryIso.CURAÇAO]: '531',
[CountryIso.CHRISTMAS_ISLAND]: '162',
[CountryIso.CAYMAN_ISLANDS]: '136',
[CountryIso.CYPRUS]: '196',
[CountryIso.CZECHIA]: '203',
[CountryIso.GERMANY]: '276',
[CountryIso.DJIBOUTI]: '262',
[CountryIso.DOMINICA]: '212',
[CountryIso.DENMARK]: '208',
[CountryIso.DOMINICAN_REPUBLIC]: '214',
[CountryIso.ALGERIA]: '012',
[CountryIso.ECUADOR]: '218',
[CountryIso.EGYPT]: '818',
[CountryIso.ERITREA]: '232',
[CountryIso.WESTERN_SAHARA]: '732',
[CountryIso.SPAIN]: '724',
[CountryIso.ESTONIA]: '233',
[CountryIso.ETHIOPIA]: '231',
[CountryIso.FINLAND]: '246',
[CountryIso.FIJI]: '242',
[CountryIso.FALKLAND_ISLANDS_MALVINAS]: '238',
[CountryIso.FRANCE]: '250',
[CountryIso.FAROE_ISLANDS]: '234',
[CountryIso.MICRONESIA_FEDERATED_STATES_OF]: '583',
[CountryIso.GABON]: '266',
[CountryIso.UNITED_KINGDOM]: '826',
[CountryIso.GEORGIA]: '268',
[CountryIso.GUERNSEY]: '831',
[CountryIso.GHANA]: '288',
[CountryIso.GIBRALTAR]: '292',
[CountryIso.GUINEA]: '324',
[CountryIso.GUADELOUPE]: '312',
[CountryIso.GAMBIA]: '270',
[CountryIso.GUINEA_BISSAU]: '624',
[CountryIso.EQUATORIAL_GUINEA]: '226',
[CountryIso.GREECE]: '300',
[CountryIso.GRENADA]: '308',
[CountryIso.GREENLAND]: '304',
[CountryIso.GUATEMALA]: '320',
[CountryIso.FRENCH_GUIANA]: '254',
[CountryIso.GUAM]: '316',
[CountryIso.GUYANA]: '328',
[CountryIso.HONG_KONG]: '344',
[CountryIso.HEARD_ISLAND_AND_MCDONALD_ISLANDS]: '334',
[CountryIso.HONDURAS]: '340',
[CountryIso.CROATIA]: '191',
[CountryIso.HAITI]: '332',
[CountryIso.HUNGARY]: '348',
[CountryIso.INDONESIA]: '360',
[CountryIso.ISLE_OF_MAN]: '833',
[CountryIso.INDIA]: '356',
[CountryIso.BRITISH_INDIAN_OCEAN_TERRITORY]: '086',
[CountryIso.IRELAND]: '372',
[CountryIso.IRAN_ISLAMIC_REPUBLIC_OF]: '364',
[CountryIso.IRAQ]: '368',
[CountryIso.ICELAND]: '352',
[CountryIso.ISRAEL]: '376',
[CountryIso.ITALY]: '380',
[CountryIso.JAMAICA]: '388',
[CountryIso.JERSEY]: '832',
[CountryIso.JORDAN]: '400',
[CountryIso.JAPAN]: '392',
[CountryIso.KAZAKHSTAN]: '398',
[CountryIso.KENYA]: '404',
[CountryIso.KYRGYZSTAN]: '417',
[CountryIso.CAMBODIA]: '116',
[CountryIso.KIRIBATI]: '296',
[CountryIso.SAINT_KITTS_AND_NEVIS]: '659',
[CountryIso.KOREA_REPUBLIC_OF]: '410',
[CountryIso.KUWAIT]: '414',
[CountryIso.LAO_PEOPLES_DEMOCRATIC_REPUBLIC]: '418',
[CountryIso.LEBANON]: '422',
[CountryIso.LIBERIA]: '430',
[CountryIso.LIBYA]: '434',
[CountryIso.SAINT_LUCIA]: '662',
[CountryIso.LIECHTENSTEIN]: '438',
[CountryIso.SRI_LANKA]: '144',
[CountryIso.LESOTHO]: '426',
[CountryIso.LITHUANIA]: '440',
[CountryIso.LUXEMBOURG]: '442',
[CountryIso.LATVIA]: '428',
[CountryIso.MACAO]: '446',
[CountryIso.SAINT_MARTIN_FRENCH_PART]: '663',
[CountryIso.MOROCCO]: '504',
[CountryIso.MONACO]: '492',
[CountryIso.MOLDOVA_REPUBLIC_OF]: '498',
[CountryIso.MADAGASCAR]: '450',
[CountryIso.MALDIVES]: '462',
[CountryIso.MEXICO]: '484',
[CountryIso.MARSHALL_ISLANDS]: '584',
[CountryIso.NORTH_MACEDONIA]: '807',
[CountryIso.MALI]: '466',
[CountryIso.MALTA]: '470',
[CountryIso.MYANMAR]: '104',
[CountryIso.MONTENEGRO]: '499',
[CountryIso.MONGOLIA]: '496',
[CountryIso.NORTHERN_MARIANA_ISLANDS]: '580',
[CountryIso.MOZAMBIQUE]: '508',
[CountryIso.MAURITANIA]: '478',
[CountryIso.MONTSERRAT]: '500',
[CountryIso.MARTINIQUE]: '474',
[CountryIso.MAURITIUS]: '480',
[CountryIso.MALAWI]: '454',
[CountryIso.MALAYSIA]: '458',
[CountryIso.MAYOTTE]: '175',
[CountryIso.NAMIBIA]: '516',
[CountryIso.NEW_CALEDONIA]: '540',
[CountryIso.NIGER]: '562',
[CountryIso.NORFOLK_ISLAND]: '574',
[CountryIso.NIGERIA]: '566',
[CountryIso.NICARAGUA]: '558',
[CountryIso.NIUE]: '570',
[CountryIso.NETHERLANDS]: '528',
[CountryIso.NORWAY]: '578',
[CountryIso.NEPAL]: '524',
[CountryIso.NAURU]: '520',
[CountryIso.NEW_ZEALAND]: '554',
[CountryIso.OMAN]: '512',
[CountryIso.PAKISTAN]: '586',
[CountryIso.PANAMA]: '591',
[CountryIso.PITCAIRN]: '612',
[CountryIso.PERU]: '604',
[CountryIso.PHILIPPINES]: '608',
[CountryIso.PALAU]: '585',
[CountryIso.PAPUA_NEW_GUINEA]: '598',
[CountryIso.POLAND]: '616',
[CountryIso.PUERTO_RICO]: '630',
[CountryIso.KOREA_DEMOCRATIC_PEOPLES_REPUBLIC_OF]: '408',
[CountryIso.PORTUGAL]: '620',
[CountryIso.PARAGUAY]: '600',
[CountryIso.PALESTINE_STATE_OF]: '275',
[CountryIso.FRENCH_POLYNESIA]: '258',
[CountryIso.QATAR]: '634',
[CountryIso.REUNION]: '638',
[CountryIso.ROMANIA]: '642',
[CountryIso.RUSSIAN_FEDERATION]: '643',
[CountryIso.RWANDA]: '646',
[CountryIso.SAUDI_ARABIA]: '682',
[CountryIso.SUDAN]: '729',
[CountryIso.SENEGAL]: '686',
[CountryIso.SINGAPORE]: '702',
[CountryIso.SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS]: '239',
[CountryIso.SAINT_HELENA_ASCENSION_AND_TRISTAN_DA_CUNHA]: '654',
[CountryIso.SVALBARD_AND_JAN_MAYEN]: '744',
[CountryIso.SOLOMON_ISLANDS]: '090',
[CountryIso.SIERRA_LEONE]: '694',
[CountryIso.EL_SALVADOR]: '222',
[CountryIso.SAN_MARINO]: '674',
[CountryIso.SOMALIA]: '706',
[CountryIso.SAINT_PIERRE_AND_MIQUELON]: '666',
[CountryIso.SERBIA]: '688',
[CountryIso.SOUTH_SUDAN]: '728',
[CountryIso.SAO_TOME_AND_PRINCIPE]: '678',
[CountryIso.SURINAME]: '740',
[CountryIso.SLOVAKIA]: '703',
[CountryIso.SLOVENIA]: '705',
[CountryIso.SWEDEN]: '752',
[CountryIso.ESWATINI]: '748',
[CountryIso.SINT_MAARTEN_DUTCH_PART]: '534',
[CountryIso.SEYCHELLES]: '690',
[CountryIso.SYRIAN_ARAB_REPUBLIC]: '760',
[CountryIso.TURKS_AND_CAICOS_ISLANDS]: '796',
[CountryIso.CHAD]: '148',
[CountryIso.TOGO]: '768',
[CountryIso.THAILAND]: '764',
[CountryIso.TAJIKISTAN]: '762',
[CountryIso.TOKELAU]: '772',
[CountryIso.TURKMENISTAN]: '795',
[CountryIso.TIMOR_LESTE]: '626',
[CountryIso.TONGA]: '776',
[CountryIso.TRINIDAD_AND_TOBAGO]: '780',
[CountryIso.TUNISIA]: '788',
[CountryIso.TURKEY]: '792',
[CountryIso.TUVALU]: '798',
[CountryIso.TAIWAN_PROVINCE_OF_CHINA]: '158',
[CountryIso.TANZANIA_UNITED_REPUBLIC_OF]: '834',
[CountryIso.UGANDA]: '800',
[CountryIso.UKRAINE]: '804',
[CountryIso.UNITED_STATES_MINOR_OUTLYING_ISLANDS]: '581',
[CountryIso.URUGUAY]: '858',
[CountryIso.UNITED_STATES]: '840',
[CountryIso.UZBEKISTAN]: '860',
[CountryIso.HOLY_SEE_VATICAN_CITY_STATE]: '336',
[CountryIso.SAINT_VINCENT_AND_THE_GRENADINES]: '670',
[CountryIso.VENEZUELA_BOLIVARIAN_REPUBLIC_OF]: '862',
[CountryIso.VIRGIN_ISLANDS_BRITISH]: '092',
[CountryIso.VIRGIN_ISLANDS_US]: '850',
[CountryIso.VIET_NAM]: '704',
[CountryIso.VANUATU]: '548',
[CountryIso.WALLIS_AND_FUTUNA]: '876',
[CountryIso.SAMOA]: '882',
[CountryIso.YEMEN]: '887',
[CountryIso.SOUTH_AFRICA]: '710',
[CountryIso.ZAMBIA]: '894',
[CountryIso.ZIMBABWE]: '716',
};

View File

@ -1 +1,2 @@
export * from './countries-numeric-iso.constant';
export * from './global.constant';

View File

@ -0,0 +1,251 @@
export enum CountryIso {
ARUBA = 'AW',
AFGHANISTAN = 'AF',
ANGOLA = 'AO',
ANGUILLA = 'AI',
ALAND_ISLANDS = 'AX',
ALBANIA = 'AL',
ANDORRA = 'AD',
UNITED_ARAB_EMIRATES = 'AE',
ARGENTINA = 'AR',
ARMENIA = 'AM',
AMERICAN_SAMOA = 'AS',
ANTARCTICA = 'AQ',
FRENCH_SOUTHERN_TERRITORIES = 'TF',
ANTIGUA_AND_BARBUDA = 'AG',
AUSTRALIA = 'AU',
AUSTRIA = 'AT',
AZERBAIJAN = 'AZ',
BURUNDI = 'BI',
BELGIUM = 'BE',
BENIN = 'BJ',
BONAIRE_SINT_EUSTATIUS_AND_SABA = 'BQ',
BURKINA_FASO = 'BF',
BANGLADESH = 'BD',
BULGARIA = 'BG',
BAHRAIN = 'BH',
BAHAMAS = 'BS',
BOSNIA_AND_HERZEGOVINA = 'BA',
SAINT_BARTHÉLEMY = 'BL',
BELARUS = 'BY',
BELIZE = 'BZ',
BERMUDA = 'BM',
BOLIVIA_PLURINATIONAL_STATE_OF = 'BO',
BRAZIL = 'BR',
BARBADOS = 'BB',
BRUNEI_DARUSSALAM = 'BN',
BHUTAN = 'BT',
BOUVET_ISLAND = 'BV',
BOTSWANA = 'BW',
CENTRAL_AFRICAN_REPUBLIC = 'CF',
CANADA = 'CA',
COCOS_KEELING_ISLANDS = 'CC',
SWITZERLAND = 'CH',
CHILE = 'CL',
CHINA = 'CN',
COTE_DIVOIRE = 'CI',
CAMEROON = 'CM',
CONGO_THE_DEMOCRATIC_REPUBLIC_OF_THE = 'CD',
CONGO = 'CG',
COOK_ISLANDS = 'CK',
COLOMBIA = 'CO',
COMOROS = 'KM',
CABO_VERDE = 'CV',
COSTA_RICA = 'CR',
CUBA = 'CU',
CURAÇAO = 'CW',
CHRISTMAS_ISLAND = 'CX',
CAYMAN_ISLANDS = 'KY',
CYPRUS = 'CY',
CZECHIA = 'CZ',
GERMANY = 'DE',
DJIBOUTI = 'DJ',
DOMINICA = 'DM',
DENMARK = 'DK',
DOMINICAN_REPUBLIC = 'DO',
ALGERIA = 'DZ',
ECUADOR = 'EC',
EGYPT = 'EG',
ERITREA = 'ER',
WESTERN_SAHARA = 'EH',
SPAIN = 'ES',
ESTONIA = 'EE',
ETHIOPIA = 'ET',
FINLAND = 'FI',
FIJI = 'FJ',
FALKLAND_ISLANDS_MALVINAS = 'FK',
FRANCE = 'FR',
FAROE_ISLANDS = 'FO',
MICRONESIA_FEDERATED_STATES_OF = 'FM',
GABON = 'GA',
UNITED_KINGDOM = 'GB',
GEORGIA = 'GE',
GUERNSEY = 'GG',
GHANA = 'GH',
GIBRALTAR = 'GI',
GUINEA = 'GN',
GUADELOUPE = 'GP',
GAMBIA = 'GM',
GUINEA_BISSAU = 'GW',
EQUATORIAL_GUINEA = 'GQ',
GREECE = 'GR',
GRENADA = 'GD',
GREENLAND = 'GL',
GUATEMALA = 'GT',
FRENCH_GUIANA = 'GF',
GUAM = 'GU',
GUYANA = 'GY',
HONG_KONG = 'HK',
HEARD_ISLAND_AND_MCDONALD_ISLANDS = 'HM',
HONDURAS = 'HN',
CROATIA = 'HR',
HAITI = 'HT',
HUNGARY = 'HU',
INDONESIA = 'ID',
ISLE_OF_MAN = 'IM',
INDIA = 'IN',
BRITISH_INDIAN_OCEAN_TERRITORY = 'IO',
IRELAND = 'IE',
IRAN_ISLAMIC_REPUBLIC_OF = 'IR',
IRAQ = 'IQ',
ICELAND = 'IS',
ISRAEL = 'IL',
ITALY = 'IT',
JAMAICA = 'JM',
JERSEY = 'JE',
JORDAN = 'JO',
JAPAN = 'JP',
KAZAKHSTAN = 'KZ',
KENYA = 'KE',
KYRGYZSTAN = 'KG',
CAMBODIA = 'KH',
KIRIBATI = 'KI',
SAINT_KITTS_AND_NEVIS = 'KN',
KOREA_REPUBLIC_OF = 'KR',
KUWAIT = 'KW',
LAO_PEOPLES_DEMOCRATIC_REPUBLIC = 'LA',
LEBANON = 'LB',
LIBERIA = 'LR',
LIBYA = 'LY',
SAINT_LUCIA = 'LC',
LIECHTENSTEIN = 'LI',
SRI_LANKA = 'LK',
LESOTHO = 'LS',
LITHUANIA = 'LT',
LUXEMBOURG = 'LU',
LATVIA = 'LV',
MACAO = 'MO',
SAINT_MARTIN_FRENCH_PART = 'MF',
MOROCCO = 'MA',
MONACO = 'MC',
MOLDOVA_REPUBLIC_OF = 'MD',
MADAGASCAR = 'MG',
MALDIVES = 'MV',
MEXICO = 'MX',
MARSHALL_ISLANDS = 'MH',
NORTH_MACEDONIA = 'MK',
MALI = 'ML',
MALTA = 'MT',
MYANMAR = 'MM',
MONTENEGRO = 'ME',
MONGOLIA = 'MN',
NORTHERN_MARIANA_ISLANDS = 'MP',
MOZAMBIQUE = 'MZ',
MAURITANIA = 'MR',
MONTSERRAT = 'MS',
MARTINIQUE = 'MQ',
MAURITIUS = 'MU',
MALAWI = 'MW',
MALAYSIA = 'MY',
MAYOTTE = 'YT',
NAMIBIA = 'NA',
NEW_CALEDONIA = 'NC',
NIGER = 'NE',
NORFOLK_ISLAND = 'NF',
NIGERIA = 'NG',
NICARAGUA = 'NI',
NIUE = 'NU',
NETHERLANDS = 'NL',
NORWAY = 'NO',
NEPAL = 'NP',
NAURU = 'NR',
NEW_ZEALAND = 'NZ',
OMAN = 'OM',
PAKISTAN = 'PK',
PANAMA = 'PA',
PITCAIRN = 'PN',
PERU = 'PE',
PHILIPPINES = 'PH',
PALAU = 'PW',
PAPUA_NEW_GUINEA = 'PG',
POLAND = 'PL',
PUERTO_RICO = 'PR',
KOREA_DEMOCRATIC_PEOPLES_REPUBLIC_OF = 'KP',
PORTUGAL = 'PT',
PARAGUAY = 'PY',
PALESTINE_STATE_OF = 'PS',
FRENCH_POLYNESIA = 'PF',
QATAR = 'QA',
REUNION = 'RE',
ROMANIA = 'RO',
RUSSIAN_FEDERATION = 'RU',
RWANDA = 'RW',
SAUDI_ARABIA = 'SA',
SUDAN = 'SD',
SENEGAL = 'SN',
SINGAPORE = 'SG',
SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS = 'GS',
SAINT_HELENA_ASCENSION_AND_TRISTAN_DA_CUNHA = 'SH',
SVALBARD_AND_JAN_MAYEN = 'SJ',
SOLOMON_ISLANDS = 'SB',
SIERRA_LEONE = 'SL',
EL_SALVADOR = 'SV',
SAN_MARINO = 'SM',
SOMALIA = 'SO',
SAINT_PIERRE_AND_MIQUELON = 'PM',
SERBIA = 'RS',
SOUTH_SUDAN = 'SS',
SAO_TOME_AND_PRINCIPE = 'ST',
SURINAME = 'SR',
SLOVAKIA = 'SK',
SLOVENIA = 'SI',
SWEDEN = 'SE',
ESWATINI = 'SZ',
SINT_MAARTEN_DUTCH_PART = 'SX',
SEYCHELLES = 'SC',
SYRIAN_ARAB_REPUBLIC = 'SY',
TURKS_AND_CAICOS_ISLANDS = 'TC',
CHAD = 'TD',
TOGO = 'TG',
THAILAND = 'TH',
TAJIKISTAN = 'TJ',
TOKELAU = 'TK',
TURKMENISTAN = 'TM',
TIMOR_LESTE = 'TL',
TONGA = 'TO',
TRINIDAD_AND_TOBAGO = 'TT',
TUNISIA = 'TN',
TURKEY = 'TR',
TUVALU = 'TV',
TAIWAN_PROVINCE_OF_CHINA = 'TW',
TANZANIA_UNITED_REPUBLIC_OF = 'TZ',
UGANDA = 'UG',
UKRAINE = 'UA',
UNITED_STATES_MINOR_OUTLYING_ISLANDS = 'UM',
URUGUAY = 'UY',
UNITED_STATES = 'US',
UZBEKISTAN = 'UZ',
HOLY_SEE_VATICAN_CITY_STATE = 'VA',
SAINT_VINCENT_AND_THE_GRENADINES = 'VC',
VENEZUELA_BOLIVARIAN_REPUBLIC_OF = 'VE',
VIRGIN_ISLANDS_BRITISH = 'VG',
VIRGIN_ISLANDS_US = 'VI',
VIET_NAM = 'VN',
VANUATU = 'VU',
WALLIS_AND_FUTUNA = 'WF',
SAMOA = 'WS',
YEMEN = 'YE',
SOUTH_AFRICA = 'ZA',
ZAMBIA = 'ZM',
ZIMBABWE = 'ZW',
}

View File

@ -0,0 +1 @@
export * from './countries-iso.enum';

View File

@ -1,3 +0,0 @@
export class NotificationEvent {
constructor(public readonly notification: Notification) {}
}

View File

@ -0,0 +1 @@
export * from './notification-created.listener';

View File

@ -0,0 +1,88 @@
// notification-created.handler.ts
import { MailerService } from '@nestjs-modules/mailer';
import { Injectable, Logger } from '@nestjs/common';
import { SendEmailRequestDto } from '~/common/modules/notification/dtos/request';
import { EventType, NotificationChannel, NotificationScope } from '~/common/modules/notification/enums';
import { FirebaseService, TwilioService } from '~/common/modules/notification/services';
import { IEventInterface } from '~/common/redis/interface';
import { DeviceService } from '~/user/services';
@Injectable()
export class NotificationCreatedListener {
private readonly logger = new Logger(NotificationCreatedListener.name);
constructor(
private readonly twilioService: TwilioService,
private readonly deviceService: DeviceService,
private readonly mailerService: MailerService,
private readonly firebaseService: FirebaseService,
) {}
/**
* Handles the NOTIFICATION_CREATED event by calling the appropriate channel logic.
*/
async handle(event: IEventInterface) {
this.logger.log(
`Handling ${EventType.NOTIFICATION_CREATED} event for notification ${event.id} (channel: ${event.channel})`,
);
switch (event.channel) {
case NotificationChannel.SMS:
return this.sendSMS(event.recipient!, event.message);
case NotificationChannel.PUSH:
return this.sendPushNotification(event.userId, event.title, event.message);
case NotificationChannel.EMAIL:
return this.sendEmail({
to: event.recipient!,
subject: event.title,
template: this.getTemplateFromNotification(event),
data: event.data,
});
}
}
private getTemplateFromNotification(notification: IEventInterface) {
switch (notification.scope) {
case NotificationScope.OTP:
return 'otp';
case NotificationScope.USER_INVITED:
return 'user-invite';
default:
return 'otp';
}
}
private async sendPushNotification(userId: string, title: string, body: string) {
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;
}
return this.firebaseService.sendNotification(tokens, title, body);
}
private async sendSMS(to: string, body: string) {
this.logger.log(`Sending SMS to ${to}`);
await this.twilioService.sendSMS(to, body);
}
private async sendEmail({ to, subject, data, template }: SendEmailRequestDto) {
this.logger.log(`Sending email to ${to}`);
try {
await this.mailerService.sendMail({
to,
subject,
template,
context: { ...data, currentYear: new Date().getFullYear() },
});
this.logger.log(`Email sent to ${to}`);
} catch (error) {
this.logger.error(`Failed to send email to ${to} error: ${JSON.stringify(error)}`);
throw error;
}
}
}

View File

@ -3,15 +3,19 @@ import { forwardRef, Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TwilioModule } from 'nestjs-twilio';
import { RedisModule } from '~/common/redis/redis.module';
import { buildMailerOptions, buildTwilioOptions } from '~/core/module-options';
import { UserModule } from '~/user/user.module';
import { NotificationsController } from './controllers';
import { Notification } from './entities';
import { NotificationCreatedListener } from './listeners';
import { NotificationsRepository } from './repositories';
import { FirebaseService, NotificationsService, TwilioService } from './services';
@Module({
imports: [
forwardRef(() => RedisModule.register()),
forwardRef(() => UserModule),
TypeOrmModule.forFeature([Notification]),
TwilioModule.forRootAsync({
useFactory: buildTwilioOptions,
@ -21,10 +25,15 @@ import { FirebaseService, NotificationsService, TwilioService } from './services
useFactory: buildMailerOptions,
inject: [ConfigService],
}),
forwardRef(() => UserModule),
],
providers: [NotificationsService, FirebaseService, NotificationsRepository, TwilioService],
exports: [NotificationsService],
providers: [
NotificationsService,
FirebaseService,
NotificationsRepository,
TwilioService,
NotificationCreatedListener,
],
exports: [NotificationsService, NotificationCreatedListener],
controllers: [NotificationsController],
})
export class NotificationModule {}

View File

@ -1,8 +1,6 @@
import { MailerService } from '@nestjs-modules/mailer';
import { Injectable, Logger } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
import { RedisPubSubService } from '~/common/redis/services';
import { PageOptionsRequestDto } from '~/core/dtos';
import { DeviceService } from '~/user/services';
import { OTP_BODY, OTP_TITLE } from '../../otp/constants';
import { OtpType } from '../../otp/enums';
import { ISendOtp } from '../../otp/interfaces';
@ -10,19 +8,15 @@ import { SendEmailRequestDto } from '../dtos/request';
import { Notification } from '../entities';
import { EventType, NotificationChannel, NotificationScope } from '../enums';
import { NotificationsRepository } from '../repositories';
import { FirebaseService } from './firebase.service';
import { TwilioService } from './twilio.service';
@Injectable()
export class NotificationsService {
private readonly logger = new Logger(NotificationsService.name);
constructor(
private readonly firebaseService: FirebaseService,
private readonly notificationRepository: NotificationsRepository,
private readonly twilioService: TwilioService,
private readonly eventEmitter: EventEmitter2,
private readonly deviceService: DeviceService,
private readonly mailerService: MailerService,
@Inject(forwardRef(() => RedisPubSubService))
private readonly redisPubSubService: RedisPubSubService,
) {}
async getNotifications(userId: string, pageOptionsDto: PageOptionsRequestDto) {
@ -56,7 +50,11 @@ export class NotificationsService {
scope: NotificationScope.USER_INVITED,
channel: NotificationChannel.EMAIL,
});
return this.eventEmitter.emit(EventType.NOTIFICATION_CREATED, notification, 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) {
@ -71,67 +69,9 @@ export class NotificationsService {
this.logger.log(`emitting ${EventType.NOTIFICATION_CREATED} event`);
return this.eventEmitter.emit(EventType.NOTIFICATION_CREATED, notification);
}
private async sendPushNotification(userId: string, title: string, body: string) {
this.logger.log(`Sending push notification to user ${userId}`);
// Get the device tokens for the user
const tokens = await this.deviceService.getTokens(userId);
if (!tokens.length) {
this.logger.log(`No device tokens found for user ${userId} but notification created in the database`);
return;
}
// Send the notification
return this.firebaseService.sendNotification(tokens, title, body);
}
private async sendSMS(to: string, body: string) {
this.logger.log(`Sending SMS to ${to}`);
await this.twilioService.sendSMS(to, body);
}
private async sendEmail({ to, subject, data, template }: SendEmailRequestDto) {
this.logger.log(`Sending email to ${to}`);
await this.mailerService.sendMail({
to,
subject,
template,
context: { ...data },
return this.redisPubSubService.publishEvent(EventType.NOTIFICATION_CREATED, {
...notification,
data: { otp },
});
this.logger.log(`Email sent to ${to}`);
}
private getTemplateFromNotification(notification: Notification) {
switch (notification.scope) {
case NotificationScope.OTP:
return 'otp';
case NotificationScope.USER_INVITED:
return 'user-invite';
default:
return 'otp';
}
}
@OnEvent(EventType.NOTIFICATION_CREATED)
handleNotificationCreatedEvent(notification: Notification, data?: any) {
this.logger.log(
`Handling ${EventType.NOTIFICATION_CREATED} event for notification ${notification.id} and type ${notification.channel}`,
);
switch (notification.channel) {
case NotificationChannel.SMS:
return this.sendSMS(notification.recipient!, notification.message);
case NotificationChannel.PUSH:
return this.sendPushNotification(notification.userId, notification.title, notification.message);
case NotificationChannel.EMAIL:
return this.sendEmail({
to: notification.recipient!,
subject: notification.title,
template: this.getTemplateFromNotification(notification),
data,
});
}
}
}

View File

@ -1,21 +1,22 @@
<body>
<div class="otp">
<h1 class="title">Your OTP Code</h1>
<p class="message">To verify your account, please use the following One-Time Password (OTP):</p>
{{>header}}
<div class="email-container">
<div class="email-body">
<h2>Your One-Time Password</h2>
<p class="instructions">
Hello! Thank you for using Zod. For security purposes, please use the following
One-Time Password (OTP) to proceed with your verification. This code is
valid for 5 minutes.
</p>
<!-- OTP CODE -->
<div class="otp-code">{{otp}}</div>
<p class="instructions">
If you did not request this code, please ignore this email or
contact our support team immediately.
</p>
</div>
</div>
<style>
.otp {
text-align: center;
font-family: sans-serif;
font-size: 16px;
line-height: 1.5;
}
.otp-code {
font-size: 24px;
font-weight: bold;
margin-top: 20px;
}
</style>
</body>
{{>footer}}

View File

@ -0,0 +1,11 @@
<table class="email-footer" role="presentation" cellpadding="0" cellspacing="0">
<tr>
<td>
<p>
&copy; 2025 Zod. All rights reserved. <br />
Need help? Contact us at
<a href="mailto:support@zod-alkhair.com">support@zod-alkhair.com</a>
</p>
</td>
</tr>
</table>

View File

@ -0,0 +1,95 @@
<head>
<meta charset="UTF-8" />
<title>Zod OTP Email</title>
<style>
/* ----- Core Reset ----- */
body, table, td, a {
font-family: Arial, sans-serif;
text-decoration: none;
}
body {
margin: 0;
padding: 0;
background-color: #F8F8F8;
}
table {
border-collapse: collapse;
width: 100%;
}
/* ----- Header ----- */
.email-header {
background-color: #7B2BFF; /* primary color */
padding: 1rem;
text-align: center;
}
.email-header h1 {
color: #FFFFFF;
margin: 0;
font-size: 1.5rem;
text-transform: uppercase;
letter-spacing: 2px;
}
/* ----- Main Container ----- */
.email-container {
max-width: 600px;
margin: 2rem auto;
background-color: #FFFFFF;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
.email-body {
padding: 2rem;
color: #444444;
}
.email-body h2 {
margin-top: 0;
color: #7B2BFF; /* primary color */
}
.otp-code {
margin: 2rem 0;
font-size: 2rem;
font-weight: bold;
color: #1570EF; /* secondary color */
text-align: center;
}
.instructions {
line-height: 1.5;
margin: 1rem 0;
}
.btn-verify {
display: inline-block;
padding: 0.75rem 1.5rem;
background-color: #1570EF; /* secondary color */
color: #FFFFFF;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
margin-top: 1rem;
}
/* ----- Footer ----- */
.email-footer {
background-color: #F8F8F8;
text-align: center;
padding: 1rem;
font-size: 0.875rem;
color: #999999;
}
.email-footer a {
color: #1570EF; /* secondary color */
}
</style>
</head>
<body>
<!-- HEADER -->
<table class="email-header" role="presentation" cellpadding="0" cellspacing="0">
<tr>
<td>
<h1>ZOD</h1>
</td>
</tr>
</table>

View File

@ -24,6 +24,9 @@ export class Otp {
@Column('varchar', { name: 'user_id' })
userId!: string;
@Column('boolean', { default: false, name: 'is_used' })
isUsed!: boolean;
@ManyToOne(() => User, (user) => user.otp, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'user_id' })
user!: User;

View File

@ -1,4 +1,6 @@
export enum OtpScope {
VERIFY_PHONE = 'VERIFY_PHONE',
VERIFY_EMAIL = 'VERIFY_EMAIL',
FORGET_PASSWORD = 'FORGET_PASSWORD',
LOGIN = 'LOGIN',
}

View File

@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MoreThan, Repository } from 'typeorm';
import { Otp } from '../entities';
import { IVerifyOtp } from '../interfaces';
import { ISendOtp, IVerifyOtp } from '../interfaces';
const FIVE = 5;
const SIXTY = 60;
const ONE_THOUSAND = 1000;
@ -14,7 +14,7 @@ export class OtpRepository {
createOtp(otp: Partial<Otp>) {
return this.otpRepository.save(
this.otpRepository.create({
userId: otp.userId,
userId: otp.userId ?? undefined,
value: otp.value,
scope: otp.scope,
otpType: otp.otpType,
@ -31,10 +31,29 @@ export class OtpRepository {
value: otp.value,
otpType: otp.otpType,
expiresAt: MoreThan(new Date()),
isUsed: false,
},
order: {
createdAt: 'DESC',
},
});
}
updateOtp(id: string, data: Partial<Otp>) {
return this.otpRepository.update(id, data);
}
invalidateOtp(otp: ISendOtp) {
return this.otpRepository.update(
{
userId: otp.userId,
scope: otp.scope,
otpType: otp.otpType,
isUsed: false,
},
{
isUsed: true,
},
);
}
}

View File

@ -15,8 +15,11 @@ export class OtpService {
private readonly otpRepository: OtpRepository,
private readonly notificationService: NotificationsService,
) {}
private useMock = this.configService.get<boolean>('USE_MOCK', false);
private useMock = [true, 'true'].includes(this.configService.get<boolean>('USE_MOCK', false));
async generateAndSendOtp(sendOtpRequest: ISendOtp): Promise<string> {
this.logger.log(`invalidate OTP for ${sendOtpRequest.recipient} and ${sendOtpRequest.otpType}`);
await this.otpRepository.invalidateOtp(sendOtpRequest);
this.logger.log(`Generating OTP for ${sendOtpRequest.recipient}`);
const otp = this.useMock ? DEFAULT_OTP_DIGIT.repeat(DEFAULT_OTP_LENGTH) : generateRandomOtp(DEFAULT_OTP_LENGTH);
@ -35,11 +38,15 @@ export class OtpService {
if (!otp) {
this.logger.error(
`OTP value ${verifyOtpRequest.value} not found for ${verifyOtpRequest.userId} and ${verifyOtpRequest.otpType}`,
`OTP value ${verifyOtpRequest.value} not found for ${verifyOtpRequest.userId} and ${verifyOtpRequest.otpType} or used`,
);
return false;
}
await this.otpRepository.updateOtp(otp.id, { isUsed: true });
this.logger.log(`OTP verified successfully for ${verifyOtpRequest.userId}`);
return !!otp;
}

View File

@ -0,0 +1,5 @@
import { Notification } from '~/common/modules/notification/entities';
export interface IEventInterface extends Notification {
data?: any;
}

View File

@ -0,0 +1 @@
export * from './event.interface';

View File

@ -0,0 +1,39 @@
// redis.module.ts (NestJS)
import { createClient } from '@keyv/redis';
import { DynamicModule, Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NotificationModule } from '../modules/notification/notification.module';
import { RedisPubSubService } from './services';
@Module({})
export class RedisModule {
static register(): DynamicModule {
return {
module: RedisModule,
providers: [
{
provide: 'REDIS_PUBLISHER',
useFactory: async (configService: ConfigService) => {
const publisher = createClient({ url: configService.get<string>('REDIS_URL') });
await publisher.connect();
return publisher;
},
inject: [ConfigService],
},
{
provide: 'REDIS_SUBSCRIBER',
useFactory: async (configService: ConfigService) => {
const subscriber = createClient({ url: configService.get<string>('REDIS_URL') });
await subscriber.connect();
return subscriber;
},
inject: [ConfigService],
},
RedisPubSubService,
],
exports: [RedisPubSubService],
imports: [NotificationModule],
};
}
}

View File

@ -0,0 +1 @@
export * from './redis-pubsub.service';

View File

@ -0,0 +1,29 @@
// redis.pubsub.service.ts (NestJS)
import { RedisClientType } from '@keyv/redis';
import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { EventType } from '~/common/modules/notification/enums';
import { NotificationCreatedListener } from '~/common/modules/notification/listeners';
import { IEventInterface } from '../interface';
@Injectable()
export class RedisPubSubService implements OnModuleInit {
private readonly logger = new Logger(RedisPubSubService.name);
constructor(
@Inject('REDIS_PUBLISHER') private readonly publisher: RedisClientType,
@Inject('REDIS_SUBSCRIBER') private readonly subscriber: RedisClientType,
private readonly notificationCreatedListener: NotificationCreatedListener,
) {}
onModuleInit() {
this.subscriber.subscribe(EventType.NOTIFICATION_CREATED, async (message) => {
const data = JSON.parse(message);
this.logger.log('Received message on NOTIFICATION_CREATED channel:', data);
await this.notificationCreatedListener.handle(data);
});
}
async publishEvent(channel: string, payload: IEventInterface) {
await this.publisher.publish(channel, JSON.stringify(payload));
}
}

View File

@ -1,7 +1,6 @@
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { ConfigService } from '@nestjs/config';
import path from 'path';
export function buildMailerOptions(config: ConfigService) {
return {
transport: {
@ -20,5 +19,13 @@ export function buildMailerOptions(config: ConfigService) {
strict: true,
},
},
options: {
partials: {
dir: path.join(__dirname, '../../common/modules/notification/templates', 'partials'),
options: {
strict: true,
},
},
},
};
}

View File

@ -1,6 +1,7 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsBoolean, IsDateString, IsEnum, IsNotEmpty, IsString, IsUUID } from 'class-validator';
import { IsBoolean, IsDateString, IsEnum, IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { CountryIso } from '~/common/enums';
import { IsAbove18 } from '~/core/decorators/validations';
import { Gender } from '~/customer/enums';
export class CreateCustomerRequestDto {
@ -16,12 +17,14 @@ export class CreateCustomerRequestDto {
@ApiProperty({ example: 'MALE' })
@IsEnum(Gender, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.gender' }) })
gender!: Gender;
@IsOptional()
gender?: Gender;
@ApiProperty({ example: 'JO' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.countryOfResidence' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.countryOfResidence' }) })
countryOfResidence!: string;
@IsEnum(CountryIso, {
message: i18n('validation.IsEnum', { path: 'general', property: 'customer.countryOfResidence' }),
})
countryOfResidence!: CountryIso;
@ApiProperty({ example: '2021-01-01' })
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.dateOfBirth' }) })
@ -31,39 +34,47 @@ export class CreateCustomerRequestDto {
@ApiProperty({ example: '999300024' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.nationalId' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.nationalId' }) })
nationalId!: string;
@IsOptional()
nationalId?: string;
@ApiProperty({ example: '2021-01-01' })
@IsDateString(
{},
{ message: i18n('validation.IsDateString', { path: 'general', property: 'junior.nationalIdExpiry' }) },
)
nationalIdExpiry!: Date;
@IsOptional()
nationalIdExpiry?: Date;
@ApiProperty({ example: 'Employee' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.sourceOfIncome' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.sourceOfIncome' }) })
sourceOfIncome!: string;
@IsOptional()
sourceOfIncome?: string;
@ApiProperty({ example: 'Accountant' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.profession' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.profession' }) })
profession!: string;
@IsOptional()
profession?: string;
@ApiProperty({ example: 'Finance' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.professionType' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.professionType' }) })
professionType!: string;
@IsOptional()
professionType?: string;
@ApiProperty({ example: false })
@IsBoolean({ message: i18n('validation.IsBoolean', { path: 'general', property: 'junior.isPep' }) })
isPep!: boolean;
@IsOptional()
isPep?: boolean;
@ApiProperty({ example: 'bf342-3f3f-3f3f-3f3f' })
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'junior.civilIdFrontId' }) })
civilIdFrontId!: string;
@IsOptional()
civilIdFrontId?: string;
@ApiProperty({ example: 'bf342-3f3f-3f3f-3f3f' })
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'junior.civilIdBackId' }) })
civilIdBackId!: string;
@IsOptional()
civilIdBackId?: string;
}

View File

@ -55,6 +55,9 @@ export class CustomerResponseDto {
@ApiProperty()
isGuardian!: boolean;
@ApiProperty()
waitingNumber!: number;
@ApiPropertyOptional({ type: DocumentMetaResponseDto })
profilePicture!: DocumentMetaResponseDto | null;
@ -76,6 +79,7 @@ export class CustomerResponseDto {
this.gender = customer.gender;
this.isJunior = customer.isJunior;
this.isGuardian = customer.isGuardian;
this.waitingNumber = customer.applicationNumber;
this.profilePicture = customer.profilePicture ? new DocumentMetaResponseDto(customer.profilePicture) : null;
}

View File

@ -1,3 +1,3 @@
export * from './customer-response.dto';
export * from './customer.response.dto';
export * from './internal.customer-details.response.dto';
export * from './internal.customer-list.response.dto';

View File

@ -3,6 +3,7 @@ import {
Column,
CreateDateColumn,
Entity,
Generated,
JoinColumn,
OneToOne,
PrimaryColumn,
@ -67,6 +68,10 @@ export class Customer extends BaseEntity {
@Column('boolean', { default: false, name: 'is_guardian' })
isGuardian!: boolean;
@Column('int', { name: 'application_number' })
@Generated('increment')
applicationNumber!: number;
@Column('varchar', { name: 'user_id' })
userId!: string;
@ -87,23 +92,23 @@ export class Customer extends BaseEntity {
@OneToOne(() => Guardian, (guardian) => guardian.customer, { cascade: true })
guardian!: Guardian;
@Column('uuid', { name: 'civil_id_front_id' })
@Column('uuid', { name: 'civil_id_front_id', nullable: true })
civilIdFrontId!: string;
@Column('uuid', { name: 'civil_id_back_id' })
@Column('uuid', { name: 'civil_id_back_id', nullable: true })
civilIdBackId!: string;
@OneToOne(() => Document, (document) => document.customerCivilIdFront)
@OneToOne(() => Document, (document) => document.customerCivilIdFront, { nullable: true })
@JoinColumn({ name: 'civil_id_front_id' })
civilIdFront!: Document;
@OneToOne(() => Document, (document) => document.customerCivilIdBack)
@OneToOne(() => Document, (document) => document.customerCivilIdBack, { nullable: true })
@JoinColumn({ name: 'civil_id_back_id' })
civilIdBack!: Document;
@CreateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
@CreateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
@UpdateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'updated_at' })
updatedAt!: Date;
}

View File

@ -29,17 +29,7 @@ export class CustomerRepository {
firstName: body.firstName,
lastName: body.lastName,
dateOfBirth: body.dateOfBirth,
gender: body.gender,
countryOfResidence: body.countryOfResidence,
nationalId: body.nationalId,
nationalIdExpiry: body.nationalIdExpiry,
sourceOfIncome: body.sourceOfIncome,
profession: body.profession,
professionType: body.professionType,
isPep: body.isPep,
civilIdFrontId: body.civilIdFrontId,
civilIdBackId: body.civilIdBackId,
}),
);
}
@ -51,7 +41,6 @@ export class CustomerRepository {
if (filters.name) {
const nameParts = filters.name.trim().split(/\s+/);
console.log(nameParts);
nameParts.length > 1
? query.andWhere('customer.firstName LIKE :firstName AND customer.lastName LIKE :lastName', {
firstName: `%${nameParts[0]}%`,

View File

@ -89,16 +89,16 @@ export class CustomerService {
}
@Transactional()
async createGuardianCustomer(userId: string, body: CreateCustomerRequestDto) {
async createGuardianCustomer(userId: string, body: Partial<CreateCustomerRequestDto>) {
this.logger.log(`Creating guardian customer for user ${userId}`);
const existingCustomer = await this.customerRepository.findOne({ id: userId });
if (existingCustomer) {
this.logger.error(`Customer ${userId} already exists`);
throw new BadRequestException('CUSTOMER.ALRADY_EXISTS');
throw new BadRequestException('CUSTOMER.ALREADY_EXISTS');
}
await this.validateCivilIdForCustomer(userId, body.civilIdFrontId, body.civilIdBackId);
// await this.validateCivilIdForCustomer(userId, body.civilIdFrontId, body.civilIdBackId);
const customer = await this.customerRepository.createCustomer(userId, body, true);
this.logger.log(`customer created for user ${userId}`);
@ -166,9 +166,12 @@ export class CustomerService {
throw new BadRequestException('CUSTOMER.CIVIL_ID_NOT_CREATED_BY_USER');
}
const customerWithTheSameId = await this.customerRepository.findCustomerByCivilId(civilIdFrontId, civilIdBackId);
const customerWithTheSameCivilId = await this.customerRepository.findCustomerByCivilId(
civilIdFrontId,
civilIdBackId,
);
if (customerWithTheSameId) {
if (customerWithTheSameCivilId) {
this.logger.error(
`Customer with civil id front ${civilIdFrontId} and civil id back ${civilIdBackId} already exists`,
);

View File

@ -1,22 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateDocumentEntity1732434281561 implements MigrationInterface {
name = 'CreateDocumentEntity1732434281561';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "documents" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" character varying(255) NOT NULL,
"extension" character varying(255) NOT NULL,
"document_type" character varying(255) NOT NULL,
"updated_at" TIMESTAMP NOT NULL DEFAULT now(),
"created_at" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "PK_ac51aa5181ee2036f5ca482857c" PRIMARY KEY ("id"))`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "documents"`);
}
}

View File

@ -1,29 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateUserEntity1733206728721 implements MigrationInterface {
name = 'CreateUserEntity1733206728721';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "users" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"email" character varying(255),
"phone_number" character varying(255) NOT NULL,
"country_code" character varying(10) NOT NULL,
"password" character varying(255),
"salt" character varying(255),
"google_id" character varying(255),
"apple_id" character varying(255),
"is_profile_completed" boolean NOT NULL DEFAULT false,
"roles" text array,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id"))`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "users" DROP CONSTRAINT "FK_02ec15de199e79a0c46869895f4"`);
await queryRunner.query(`DROP TABLE "users"`);
}
}

View File

@ -1,30 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateOtpEntity1733209041336 implements MigrationInterface {
name = 'CreateOtpEntity1733209041336';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE "otp"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"value" character varying(255) NOT NULL,
"scope" character varying(255) NOT NULL,
"otp_type" character varying(255) NOT NULL,
"expires_at" TIMESTAMP WITH TIME ZONE NOT NULL,
"user_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_32556d9d7b22031d7d0e1fd6723" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE INDEX "IDX_6427c192ef35355ebac18fb683" ON "otp" ("scope") `);
await queryRunner.query(`CREATE INDEX "IDX_258d028d322ea3b856bf9f12f2" ON "otp" ("user_id") `);
await queryRunner.query(
`ALTER TABLE "otp" ADD CONSTRAINT "FK_258d028d322ea3b856bf9f12f25" 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 "otp" DROP CONSTRAINT "FK_258d028d322ea3b856bf9f12f25"`);
await queryRunner.query(`DROP INDEX "public"."IDX_258d028d322ea3b856bf9f12f2"`);
await queryRunner.query(`DROP INDEX "public"."IDX_6427c192ef35355ebac18fb683"`);
await queryRunner.query(`DROP TABLE "otp"`);
}
}

View File

@ -1,46 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateCustomerEntity1733298524771 implements MigrationInterface {
name = 'CreateCustomerEntity1733298524771';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "customers"
("id" uuid NOT NULL,
"customer_status" character varying(255) NOT NULL DEFAULT 'PENDING',
"rejection_reason" text,
"first_name" character varying(255),
"last_name" character varying(255),
"date_of_birth" date,
"national_id" character varying(255),
"national_id_expiry" date,
"country_of_residence" character varying(255),
"source_of_income" character varying(255),
"profession" character varying(255),
"profession_type" character varying(255),
"is_pep" boolean NOT NULL DEFAULT false,
"gender" character varying(255),
"is_junior" boolean NOT NULL DEFAULT false,
"is_guardian" boolean NOT NULL DEFAULT false,
"profile_picture_id" uuid,
"user_id" uuid NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "REL_5d1f609371a285123294fddcf3" UNIQUE ("user_id"),
CONSTRAINT "REL_02ec15de199e79a0c46869895f" UNIQUE ("profile_picture_id"),
CONSTRAINT "PK_a7a13f4cacb744524e44dfdad32" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "customers" ADD CONSTRAINT "FK_e7574892da11dd01de5cfc46499" FOREIGN KEY ("profile_picture_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "customers" ADD CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661" 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 "customers" DROP CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_e7574892da11dd01de5cfc46499"`);
await queryRunner.query(`DROP TABLE "customers"`);
}
}

View File

@ -1,27 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateDeviceEntity1733314952318 implements MigrationInterface {
name = 'CreateDeviceEntity1733314952318';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "devices"
("deviceId" character varying(255) NOT NULL,
"user_id" uuid NOT NULL,
"device_name" character varying,
"public_key" character varying,
"last_access_on" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_666c9b59efda8ca85b29157152c" PRIMARY KEY ("deviceId"))`,
);
await queryRunner.query(
`ALTER TABLE "devices" ADD CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c" 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 "devices" DROP CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c"`);
await queryRunner.query(`DROP TABLE "devices"`);
}
}

View File

@ -1,37 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateJuniorEntity1733731507261 implements MigrationInterface {
name = 'CreateJuniorEntity1733731507261';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "juniors"
("id" uuid NOT NULL,
"relationship" character varying(255) NOT NULL,
"civil_id_front_id" uuid NOT NULL,
"civil_id_back_id" uuid NOT NULL,
"customer_id" uuid NOT NULL,
"created_at" TIMESTAMP NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "REL_6a72e1a5758643737cc563b96c" UNIQUE ("civil_id_front_id"),
CONSTRAINT "REL_4662c4433223c01fe69fc1382f" UNIQUE ("civil_id_back_id"),
CONSTRAINT "REL_dfbf64ede1ff823a489902448a" UNIQUE ("customer_id"), CONSTRAINT "PK_2d273092322c1f8bf26296fa608" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_6a72e1a5758643737cc563b96c7" FOREIGN KEY ("civil_id_front_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_4662c4433223c01fe69fc1382f5" FOREIGN KEY ("civil_id_back_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_dfbf64ede1ff823a489902448a2" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_dfbf64ede1ff823a489902448a2"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_4662c4433223c01fe69fc1382f5"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_6a72e1a5758643737cc563b96c7"`);
await queryRunner.query(`DROP TABLE "juniors"`);
}
}

View File

@ -1,30 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateGuardianEntity1733732021622 implements MigrationInterface {
name = 'CreateGuardianEntity1733732021622';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "guardians"
("id" uuid NOT NULL,
"customer_id" uuid NOT NULL,
"created_at" TIMESTAMP NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "REL_6c46a1b6af00e6457cb1b70f7e" UNIQUE ("customer_id"), CONSTRAINT "PK_3dcf02f3dc96a2c017106f280be" PRIMARY KEY ("id"))`,
);
await queryRunner.query(`ALTER TABLE "juniors" ADD "guardian_id" uuid NOT NULL`);
await queryRunner.query(
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_0b11aa56264184690e2220da4a0" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "guardians" ADD CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "guardians" DROP CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_0b11aa56264184690e2220da4a0"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP COLUMN "guardian_id"`);
await queryRunner.query(`DROP TABLE "guardians"`);
}
}

View File

@ -1,28 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateThemeEntity1733748083604 implements MigrationInterface {
name = 'CreateThemeEntity1733748083604';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "themes"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"color" character varying(255) NOT NULL,
"avatar_id" uuid, "junior_id" uuid NOT NULL,
CONSTRAINT "REL_73fcb76399a308cdd2d431a8f2" UNIQUE ("junior_id"),
CONSTRAINT "PK_ddbeaab913c18682e5c88155592" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "themes" ADD CONSTRAINT "FK_169b672cc28cc757e1f4464864d" FOREIGN KEY ("avatar_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "themes" ADD CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e"`);
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_169b672cc28cc757e1f4464864d"`);
await queryRunner.query(`DROP TABLE "themes"`);
}
}

View File

@ -0,0 +1,249 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class InitialMigration1733750228289 implements MigrationInterface {
name = 'InitialMigration1733750228289';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "gift_replies" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "status" character varying NOT NULL DEFAULT 'PENDING', "color" character varying NOT NULL, "gift_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "REL_8292da97f1ceb9a806b8bc812f" UNIQUE ("gift_id"), CONSTRAINT "PK_ec6567bb5ab318bb292fa6599a2" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "gift" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "description" text NOT NULL, "color" character varying NOT NULL, "amount" numeric(10,3) NOT NULL, "status" character varying NOT NULL DEFAULT 'AVAILABLE', "redeemed_at" TIMESTAMP WITH TIME ZONE, "giver_id" uuid NOT NULL, "image_id" uuid NOT NULL, "recipient_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_f91217caddc01a085837ebe0606" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "gift_redemptions" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "gift_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_6ad7ac76169c3a224ce4a3afff4" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "saving_goals" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "description" character varying(255), "due_date" TIMESTAMP WITH TIME ZONE NOT NULL, "target_amount" numeric(12,3) NOT NULL, "current_amount" numeric(12,3) NOT NULL DEFAULT '0', "image_id" uuid, "junior_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_5193f14c1c3a38e6657a159795e" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "categories" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "type" character varying(255) NOT NULL, "junior_id" uuid, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_24dbc6126a28ff948da33e97d3b" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "task_submissions" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "status" character varying NOT NULL, "submitted_at" TIMESTAMP WITH TIME ZONE NOT NULL, "task_id" uuid NOT NULL, "proof_of_completion_id" uuid, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "REL_d6cfaee118a0300d652e28ee16" UNIQUE ("task_id"), CONSTRAINT "PK_8d19d6b5dd776e373113de50018" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "tasks" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "title" character varying(255) NOT NULL, "description" character varying(255) NOT NULL, "reward_amount" numeric(12,3) NOT NULL, "image_id" uuid NOT NULL, "task_frequency" character varying NOT NULL, "start_date" TIMESTAMP WITH TIME ZONE NOT NULL, "due_date" TIMESTAMP WITH TIME ZONE NOT NULL, "is_proof_required" boolean NOT NULL, "assigned_to_id" uuid NOT NULL, "assigned_by_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_8d12ff38fcc62aaba2cab748772" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "notifications" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "title" character varying NOT NULL, "message" character varying NOT NULL, "recipient" character varying, "scope" character varying NOT NULL, "status" character varying, "channel" character varying NOT NULL, "user_id" uuid, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_6a72c3c0f683f6462415e653c3a" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "otp" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "value" character varying(255) NOT NULL, "scope" character varying(255) NOT NULL, "otp_type" character varying(255) NOT NULL, "expires_at" TIMESTAMP WITH TIME ZONE NOT NULL, "user_id" uuid NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_32556d9d7b22031d7d0e1fd6723" PRIMARY KEY ("id"))`,
);
await queryRunner.query(`CREATE INDEX "IDX_6427c192ef35355ebac18fb683" ON "otp" ("scope") `);
await queryRunner.query(`CREATE INDEX "IDX_258d028d322ea3b856bf9f12f2" ON "otp" ("user_id") `);
await queryRunner.query(
`CREATE TABLE "user_registration_tokens" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "token" character varying(255) NOT NULL, "user_type" character varying(255) NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "expiry_date" TIMESTAMP NOT NULL, "user_id" uuid, "junior_id" uuid, "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "created_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "UQ_5881556d05b46fc7bd9e3bba935" UNIQUE ("token"), CONSTRAINT "PK_135a2d86443071ff0ba1c14135c" PRIMARY KEY ("id"))`,
);
await queryRunner.query(`CREATE INDEX "IDX_5881556d05b46fc7bd9e3bba93" ON "user_registration_tokens" ("token") `);
await queryRunner.query(
`CREATE TABLE "users" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "email" character varying(255), "phone_number" character varying(255), "country_code" character varying(10), "password" character varying(255), "salt" character varying(255), "google_id" character varying(255), "apple_id" character varying(255), "is_phone_verified" boolean NOT NULL DEFAULT false, "is_email_verified" boolean NOT NULL DEFAULT false, "is_profile_completed" boolean NOT NULL DEFAULT false, "is_email_enabled" boolean NOT NULL DEFAULT false, "is_push_enabled" boolean NOT NULL DEFAULT false, "is_sms_enabled" boolean NOT NULL DEFAULT false, "roles" text array, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "devices" ("deviceId" character varying(255) NOT NULL, "user_id" uuid NOT NULL, "device_name" character varying, "public_key" character varying, "fcm_token" character varying, "last_access_on" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_666c9b59efda8ca85b29157152c" PRIMARY KEY ("deviceId"))`,
);
await queryRunner.query(
`CREATE TABLE "documents" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "extension" character varying(255) NOT NULL, "document_type" character varying(255) NOT NULL, "created_by_id" uuid, "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "created_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_ac51aa5181ee2036f5ca482857c" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "customers" ("id" uuid NOT NULL, "customer_status" character varying(255) NOT NULL DEFAULT 'PENDING', "kyc_status" character varying(255) NOT NULL DEFAULT 'PENDING', "rejection_reason" text, "first_name" character varying(255), "last_name" character varying(255), "date_of_birth" date, "national_id" character varying(255), "national_id_expiry" date, "country_of_residence" character varying(255), "source_of_income" character varying(255), "profession" character varying(255), "profession_type" character varying(255), "is_pep" boolean NOT NULL DEFAULT false, "gender" character varying(255), "is_junior" boolean NOT NULL DEFAULT false, "is_guardian" boolean NOT NULL DEFAULT false, "application_number" SERIAL NOT NULL, "user_id" uuid NOT NULL, "profile_picture_id" uuid, "civil_id_front_id" uuid, "civil_id_back_id" uuid, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "REL_e7574892da11dd01de5cfc4649" UNIQUE ("profile_picture_id"), CONSTRAINT "REL_11d81cd7be87b6f8865b0cf766" UNIQUE ("user_id"), CONSTRAINT "REL_d5f99c497892ce31598ba19a72" UNIQUE ("civil_id_front_id"), CONSTRAINT "REL_2191662d124c56dd968ba01bf1" UNIQUE ("civil_id_back_id"), CONSTRAINT "PK_133ec679a801fab5e070f73d3ea" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "money_requests" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "requested_amount" numeric(10,3) NOT NULL, "message" character varying NOT NULL, "frequency" character varying NOT NULL DEFAULT 'ONE_TIME', "status" character varying NOT NULL DEFAULT 'PENDING', "reviewed_at" TIMESTAMP WITH TIME ZONE, "start_date" TIMESTAMP WITH TIME ZONE, "end_date" TIMESTAMP WITH TIME ZONE, "requester_id" uuid NOT NULL, "reviewer_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_28cff23e9fb06cd5dbf73cd53e7" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "themes" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "color" character varying(255) NOT NULL, "avatar_id" uuid, "junior_id" uuid NOT NULL, CONSTRAINT "REL_73fcb76399a308cdd2d431a8f2" UNIQUE ("junior_id"), CONSTRAINT "PK_ddbeaab913c18682e5c88155592" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "juniors" ("id" uuid NOT NULL, "relationship" character varying(255) NOT NULL, "customer_id" uuid NOT NULL, "guardian_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "REL_dfbf64ede1ff823a489902448a" UNIQUE ("customer_id"), CONSTRAINT "PK_2d273092322c1f8bf26296fa608" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "allowances" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying(255) NOT NULL, "amount" numeric(10,2) NOT NULL, "frequency" character varying(255) NOT NULL, "type" character varying(255) NOT NULL, "start_date" TIMESTAMP WITH TIME ZONE NOT NULL, "end_date" TIMESTAMP WITH TIME ZONE, "number_of_transactions" integer, "guardian_id" uuid NOT NULL, "junior_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "deleted_at" TIMESTAMP WITH TIME ZONE, CONSTRAINT "PK_3731e781e7c4e932ba4d4213ac1" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "allowance_change_requests" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "reason" text NOT NULL, "amount" numeric(10,2) NOT NULL, "status" character varying(255) NOT NULL DEFAULT 'PENDING', "allowance_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_664715670e1e72c64ce65a078de" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "guardians" ("id" uuid NOT NULL, "customer_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "REL_6c46a1b6af00e6457cb1b70f7e" UNIQUE ("customer_id"), CONSTRAINT "PK_3dcf02f3dc96a2c017106f280be" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "saving_goals_categories" ("saving_goal_id" uuid NOT NULL, "category_id" uuid NOT NULL, CONSTRAINT "PK_a49d4f57d06d0a36a8385b6c28f" PRIMARY KEY ("saving_goal_id", "category_id"))`,
);
await queryRunner.query(
`CREATE INDEX "IDX_d421de423f21c01672ea7c2e98" ON "saving_goals_categories" ("saving_goal_id") `,
);
await queryRunner.query(
`CREATE INDEX "IDX_b0a721a8f7f5b6fe93f3603ebc" ON "saving_goals_categories" ("category_id") `,
);
await queryRunner.query(
`ALTER TABLE "gift_replies" ADD CONSTRAINT "FK_8292da97f1ceb9a806b8bc812f2" FOREIGN KEY ("gift_id") REFERENCES "gift"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift" ADD CONSTRAINT "FK_0d317b68508819308455db9b9be" FOREIGN KEY ("giver_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift" ADD CONSTRAINT "FK_4a46b5734fb573dc956904c18d0" FOREIGN KEY ("recipient_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift" ADD CONSTRAINT "FK_83bb54c127d0e6ee487b90e2996" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift_redemptions" ADD CONSTRAINT "FK_243c4349f0c45ce5385ac316aaa" FOREIGN KEY ("gift_id") REFERENCES "gift"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "saving_goals" ADD CONSTRAINT "FK_dad35932272342c1a247a2cee1c" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "saving_goals" ADD CONSTRAINT "FK_f494ba0a361b2f9cbe5f6e56e38" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "categories" ADD CONSTRAINT "FK_4f98e0b010d5e90cae0a2007748" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "task_submissions" ADD CONSTRAINT "FK_d6cfaee118a0300d652e28ee166" FOREIGN KEY ("task_id") REFERENCES "tasks"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "task_submissions" ADD CONSTRAINT "FK_87876dfe440de7aafce216e9f58" FOREIGN KEY ("proof_of_completion_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_f1f00d41b1e95d0bbda2710a62b" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_9430f12c5a1604833f64595a57f" FOREIGN KEY ("assigned_to_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_3e08a7ca125a175cf899b09f71a" FOREIGN KEY ("assigned_by_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "notifications" ADD CONSTRAINT "FK_9a8a82462cab47c73d25f49261f" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "otp" ADD CONSTRAINT "FK_258d028d322ea3b856bf9f12f25" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "user_registration_tokens" ADD CONSTRAINT "FK_57cbbe079a7945d6ed1df114825" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "user_registration_tokens" ADD CONSTRAINT "FK_e41bec3ed6e549cbf90f57cc344" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "devices" ADD CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "documents" ADD CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "customers" ADD CONSTRAINT "FK_e7574892da11dd01de5cfc46499" FOREIGN KEY ("profile_picture_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "customers" ADD CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "customers" ADD CONSTRAINT "FK_d5f99c497892ce31598ba19a72c" FOREIGN KEY ("civil_id_front_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "customers" ADD CONSTRAINT "FK_2191662d124c56dd968ba01bf18" FOREIGN KEY ("civil_id_back_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_5cce02836c6033b6e2412995e34" FOREIGN KEY ("requester_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_75ba0766db9a7bf03126facf31c" FOREIGN KEY ("reviewer_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "themes" ADD CONSTRAINT "FK_169b672cc28cc757e1f4464864d" FOREIGN KEY ("avatar_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "themes" ADD CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_dfbf64ede1ff823a489902448a2" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "juniors" ADD CONSTRAINT "FK_0b11aa56264184690e2220da4a0" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "allowances" ADD CONSTRAINT "FK_80b144a74e630ed63311e97427b" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "allowances" ADD CONSTRAINT "FK_61e6e612f6d4644f8910d453cc9" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "allowance_change_requests" ADD CONSTRAINT "FK_4ea6382927f50cb93873fae16d2" FOREIGN KEY ("allowance_id") REFERENCES "allowances"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "guardians" ADD CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "saving_goals_categories" ADD CONSTRAINT "FK_d421de423f21c01672ea7c2e98f" FOREIGN KEY ("saving_goal_id") REFERENCES "saving_goals"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
);
await queryRunner.query(
`ALTER TABLE "saving_goals_categories" ADD CONSTRAINT "FK_b0a721a8f7f5b6fe93f3603ebc8" FOREIGN KEY ("category_id") REFERENCES "categories"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "saving_goals_categories" DROP CONSTRAINT "FK_b0a721a8f7f5b6fe93f3603ebc8"`);
await queryRunner.query(`ALTER TABLE "saving_goals_categories" DROP CONSTRAINT "FK_d421de423f21c01672ea7c2e98f"`);
await queryRunner.query(`ALTER TABLE "guardians" DROP CONSTRAINT "FK_6c46a1b6af00e6457cb1b70f7e7"`);
await queryRunner.query(`ALTER TABLE "allowance_change_requests" DROP CONSTRAINT "FK_4ea6382927f50cb93873fae16d2"`);
await queryRunner.query(`ALTER TABLE "allowances" DROP CONSTRAINT "FK_61e6e612f6d4644f8910d453cc9"`);
await queryRunner.query(`ALTER TABLE "allowances" DROP CONSTRAINT "FK_80b144a74e630ed63311e97427b"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_0b11aa56264184690e2220da4a0"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_dfbf64ede1ff823a489902448a2"`);
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_73fcb76399a308cdd2d431a8f2e"`);
await queryRunner.query(`ALTER TABLE "themes" DROP CONSTRAINT "FK_169b672cc28cc757e1f4464864d"`);
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_75ba0766db9a7bf03126facf31c"`);
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_5cce02836c6033b6e2412995e34"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_2191662d124c56dd968ba01bf18"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_d5f99c497892ce31598ba19a72c"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_11d81cd7be87b6f8865b0cf7661"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_e7574892da11dd01de5cfc46499"`);
await queryRunner.query(`ALTER TABLE "documents" DROP CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220"`);
await queryRunner.query(`ALTER TABLE "devices" DROP CONSTRAINT "FK_5e9bee993b4ce35c3606cda194c"`);
await queryRunner.query(`ALTER TABLE "user_registration_tokens" DROP CONSTRAINT "FK_e41bec3ed6e549cbf90f57cc344"`);
await queryRunner.query(`ALTER TABLE "user_registration_tokens" DROP CONSTRAINT "FK_57cbbe079a7945d6ed1df114825"`);
await queryRunner.query(`ALTER TABLE "otp" DROP CONSTRAINT "FK_258d028d322ea3b856bf9f12f25"`);
await queryRunner.query(`ALTER TABLE "notifications" DROP CONSTRAINT "FK_9a8a82462cab47c73d25f49261f"`);
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_3e08a7ca125a175cf899b09f71a"`);
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_9430f12c5a1604833f64595a57f"`);
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_f1f00d41b1e95d0bbda2710a62b"`);
await queryRunner.query(`ALTER TABLE "task_submissions" DROP CONSTRAINT "FK_87876dfe440de7aafce216e9f58"`);
await queryRunner.query(`ALTER TABLE "task_submissions" DROP CONSTRAINT "FK_d6cfaee118a0300d652e28ee166"`);
await queryRunner.query(`ALTER TABLE "categories" DROP CONSTRAINT "FK_4f98e0b010d5e90cae0a2007748"`);
await queryRunner.query(`ALTER TABLE "saving_goals" DROP CONSTRAINT "FK_f494ba0a361b2f9cbe5f6e56e38"`);
await queryRunner.query(`ALTER TABLE "saving_goals" DROP CONSTRAINT "FK_dad35932272342c1a247a2cee1c"`);
await queryRunner.query(`ALTER TABLE "gift_redemptions" DROP CONSTRAINT "FK_243c4349f0c45ce5385ac316aaa"`);
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_83bb54c127d0e6ee487b90e2996"`);
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_4a46b5734fb573dc956904c18d0"`);
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_0d317b68508819308455db9b9be"`);
await queryRunner.query(`ALTER TABLE "gift_replies" DROP CONSTRAINT "FK_8292da97f1ceb9a806b8bc812f2"`);
await queryRunner.query(`DROP INDEX "public"."IDX_b0a721a8f7f5b6fe93f3603ebc"`);
await queryRunner.query(`DROP INDEX "public"."IDX_d421de423f21c01672ea7c2e98"`);
await queryRunner.query(`DROP TABLE "saving_goals_categories"`);
await queryRunner.query(`DROP TABLE "guardians"`);
await queryRunner.query(`DROP TABLE "allowance_change_requests"`);
await queryRunner.query(`DROP TABLE "allowances"`);
await queryRunner.query(`DROP TABLE "juniors"`);
await queryRunner.query(`DROP TABLE "themes"`);
await queryRunner.query(`DROP TABLE "money_requests"`);
await queryRunner.query(`DROP TABLE "customers"`);
await queryRunner.query(`DROP TABLE "documents"`);
await queryRunner.query(`DROP TABLE "devices"`);
await queryRunner.query(`DROP TABLE "users"`);
await queryRunner.query(`DROP INDEX "public"."IDX_5881556d05b46fc7bd9e3bba93"`);
await queryRunner.query(`DROP TABLE "user_registration_tokens"`);
await queryRunner.query(`DROP INDEX "public"."IDX_258d028d322ea3b856bf9f12f2"`);
await queryRunner.query(`DROP INDEX "public"."IDX_6427c192ef35355ebac18fb683"`);
await queryRunner.query(`DROP TABLE "otp"`);
await queryRunner.query(`DROP TABLE "notifications"`);
await queryRunner.query(`DROP TABLE "tasks"`);
await queryRunner.query(`DROP TABLE "task_submissions"`);
await queryRunner.query(`DROP TABLE "categories"`);
await queryRunner.query(`DROP TABLE "saving_goals"`);
await queryRunner.query(`DROP TABLE "gift_redemptions"`);
await queryRunner.query(`DROP TABLE "gift"`);
await queryRunner.query(`DROP TABLE "gift_replies"`);
}
}

View File

@ -1,39 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateTaskEntities1733904556416 implements MigrationInterface {
name = 'CreateTaskEntities1733904556416';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "task_submissions" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "status" character varying NOT NULL, "submitted_at" TIMESTAMP WITH TIME ZONE NOT NULL, "task_id" uuid NOT NULL, "proof_of_completion_id" uuid, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "REL_d6cfaee118a0300d652e28ee16" UNIQUE ("task_id"), CONSTRAINT "PK_8d19d6b5dd776e373113de50018" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "tasks" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "title" character varying(255) NOT NULL, "description" character varying(255) NOT NULL, "reward_amount" numeric(12,3) NOT NULL, "image_id" uuid NOT NULL, "task_frequency" character varying NOT NULL, "start_date" date NOT NULL, "due_date" date NOT NULL, "is_proof_required" boolean NOT NULL, "assigned_to_id" uuid NOT NULL, "assigned_by_id" uuid NOT NULL, "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_8d12ff38fcc62aaba2cab748772" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "task_submissions" ADD CONSTRAINT "FK_d6cfaee118a0300d652e28ee166" FOREIGN KEY ("task_id") REFERENCES "tasks"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "task_submissions" ADD CONSTRAINT "FK_87876dfe440de7aafce216e9f58" FOREIGN KEY ("proof_of_completion_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_f1f00d41b1e95d0bbda2710a62b" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_9430f12c5a1604833f64595a57f" FOREIGN KEY ("assigned_to_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "tasks" ADD CONSTRAINT "FK_3e08a7ca125a175cf899b09f71a" FOREIGN KEY ("assigned_by_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_3e08a7ca125a175cf899b09f71a"`);
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_9430f12c5a1604833f64595a57f"`);
await queryRunner.query(`ALTER TABLE "tasks" DROP CONSTRAINT "FK_f1f00d41b1e95d0bbda2710a62b"`);
await queryRunner.query(`ALTER TABLE "task_submissions" DROP CONSTRAINT "FK_87876dfe440de7aafce216e9f58"`);
await queryRunner.query(`ALTER TABLE "task_submissions" DROP CONSTRAINT "FK_d6cfaee118a0300d652e28ee166"`);
await queryRunner.query(`DROP TABLE "tasks"`);
await queryRunner.query(`DROP TABLE "task_submissions"`);
}
}

View File

@ -1,29 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateCustomerNotificationsSettingsTable1733993920226 implements MigrationInterface {
name = 'CreateCustomerNotificationsSettingsTable1733993920226';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "cutsomer_notification_settings"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"is_email_enabled" boolean NOT NULL DEFAULT false,
"is_push_enabled" boolean NOT NULL DEFAULT false,
"is_sms_enabled" boolean NOT NULL DEFAULT false,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"customer_id" uuid, CONSTRAINT "REL_32f2b707407298a9eecd6cc7ea" UNIQUE ("customer_id"),
CONSTRAINT "PK_ea94fb22410c89ae6b37d63b0e3" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "cutsomer_notification_settings" ADD CONSTRAINT "FK_32f2b707407298a9eecd6cc7ea6" FOREIGN KEY ("customer_id") REFERENCES "customers"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "cutsomer_notification_settings" DROP CONSTRAINT "FK_32f2b707407298a9eecd6cc7ea6"`,
);
await queryRunner.query(`DROP TABLE "cutsomer_notification_settings"`);
}
}

View File

@ -1,70 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateSavingGoalsEntities1734246386471 implements MigrationInterface {
name = 'CreateSavingGoalsEntities1734246386471';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "saving_goals"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" character varying(255) NOT NULL,
"description" character varying(255),
"due_date" date NOT NULL,
"target_amount" numeric(12,3) NOT NULL,
"current_amount" numeric(12,3) NOT NULL DEFAULT '0',
"image_id" uuid, "junior_id" uuid NOT NULL,
"created_at" TIMESTAMP NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "PK_5193f14c1c3a38e6657a159795e" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "categories"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" character varying(255) NOT NULL,
"type" character varying(255) NOT NULL,
"created_at" TIMESTAMP NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP NOT NULL DEFAULT now(),
"junior_id" uuid, CONSTRAINT "PK_24dbc6126a28ff948da33e97d3b" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "saving_goals_categories"
("saving_goal_id" uuid NOT NULL,
"category_id" uuid NOT NULL,
CONSTRAINT "PK_a49d4f57d06d0a36a8385b6c28f" PRIMARY KEY ("saving_goal_id", "category_id"))`,
);
await queryRunner.query(
`CREATE INDEX "IDX_d421de423f21c01672ea7c2e98" ON "saving_goals_categories" ("saving_goal_id") `,
);
await queryRunner.query(
`CREATE INDEX "IDX_b0a721a8f7f5b6fe93f3603ebc" ON "saving_goals_categories" ("category_id") `,
);
await queryRunner.query(
`ALTER TABLE "saving_goals" ADD CONSTRAINT "FK_dad35932272342c1a247a2cee1c" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "saving_goals" ADD CONSTRAINT "FK_f494ba0a361b2f9cbe5f6e56e38" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "categories" ADD CONSTRAINT "FK_4f98e0b010d5e90cae0a2007748" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "saving_goals_categories" ADD CONSTRAINT "FK_d421de423f21c01672ea7c2e98f" FOREIGN KEY ("saving_goal_id") REFERENCES "saving_goals"("id") ON DELETE CASCADE ON UPDATE CASCADE`,
);
await queryRunner.query(
`ALTER TABLE "saving_goals_categories" ADD CONSTRAINT "FK_b0a721a8f7f5b6fe93f3603ebc8" FOREIGN KEY ("category_id") REFERENCES "categories"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "saving_goals_categories" DROP CONSTRAINT "FK_b0a721a8f7f5b6fe93f3603ebc8"`);
await queryRunner.query(`ALTER TABLE "saving_goals_categories" DROP CONSTRAINT "FK_d421de423f21c01672ea7c2e98f"`);
await queryRunner.query(`ALTER TABLE "categories" DROP CONSTRAINT "FK_4f98e0b010d5e90cae0a2007748"`);
await queryRunner.query(`ALTER TABLE "saving_goals" DROP CONSTRAINT "FK_f494ba0a361b2f9cbe5f6e56e38"`);
await queryRunner.query(`ALTER TABLE "saving_goals" DROP CONSTRAINT "FK_dad35932272342c1a247a2cee1c"`);
await queryRunner.query(`DROP INDEX "public"."IDX_b0a721a8f7f5b6fe93f3603ebc"`);
await queryRunner.query(`DROP INDEX "public"."IDX_d421de423f21c01672ea7c2e98"`);
await queryRunner.query(`DROP TABLE "saving_goals_categories"`);
await queryRunner.query(`DROP TABLE "categories"`);
await queryRunner.query(`DROP TABLE "saving_goals"`);
}
}

View File

@ -1,32 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateJuniorRegistrationTokenTable1734262619426 implements MigrationInterface {
name = 'CreateJuniorRegistrationTokenTable1734262619426';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "junior_registration_tokens"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"token" character varying(255) NOT NULL,
"is_used" boolean NOT NULL DEFAULT false,
"expiry_date" TIMESTAMP NOT NULL,
"junior_id" uuid NOT NULL,
"updated_at" TIMESTAMP NOT NULL DEFAULT now(),
"created_at" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "UQ_e6a3e23d5a63be76812dc5d7728" UNIQUE ("token"),
CONSTRAINT "PK_610992ebec8f664113ae48b946f" PRIMARY KEY ("id"))`,
);
await queryRunner.query(`CREATE INDEX "IDX_e6a3e23d5a63be76812dc5d772" ON "junior_registration_tokens" ("token") `);
await queryRunner.query(
`ALTER TABLE "junior_registration_tokens" ADD CONSTRAINT "FK_19c52317b5b7aeecc0a11789b53" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "junior_registration_tokens" DROP CONSTRAINT "FK_19c52317b5b7aeecc0a11789b53"`,
);
await queryRunner.query(`DROP INDEX "public"."IDX_e6a3e23d5a63be76812dc5d772"`);
await queryRunner.query(`DROP TABLE "junior_registration_tokens"`);
}
}

View File

@ -1,36 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateMoneyRequestEntity1734503895302 implements MigrationInterface {
name = 'CreateMoneyRequestEntity1734503895302';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "money_requests"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"requested_amount" numeric(10,3) NOT NULL,
"message" character varying NOT NULL,
"frequency" character varying NOT NULL DEFAULT 'ONE_TIME',
"status" character varying NOT NULL DEFAULT 'PENDING',
"reviewed_at" TIMESTAMP WITH TIME ZONE,
"start_date" TIMESTAMP WITH TIME ZONE,
"end_date" TIMESTAMP WITH TIME ZONE,
"requester_id" uuid NOT NULL,
"reviewer_id" uuid NOT NULL,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_28cff23e9fb06cd5dbf73cd53e7" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_5cce02836c6033b6e2412995e34" FOREIGN KEY ("requester_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_75ba0766db9a7bf03126facf31c" FOREIGN KEY ("reviewer_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_75ba0766db9a7bf03126facf31c"`);
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_5cce02836c6033b6e2412995e34"`);
await queryRunner.query(`DROP TABLE "money_requests"`);
}
}

View File

@ -1,53 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateAllowanceEntities1734601976591 implements MigrationInterface {
name = 'CreateAllowanceEntities1734601976591';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "allowances"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" character varying(255) NOT NULL,
"amount" numeric(10,2) NOT NULL,
"frequency" character varying(255) NOT NULL,
"type" character varying(255) NOT NULL,
"start_date" TIMESTAMP WITH TIME ZONE NOT NULL,
"end_date" TIMESTAMP WITH TIME ZONE,
"number_of_transactions" integer,
"guardian_id" uuid NOT NULL,
"junior_id" uuid NOT NULL,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"deleted_at" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "PK_3731e781e7c4e932ba4d4213ac1" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "allowance_change_requests"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"reason" text NOT NULL,
"amount" numeric(10,2) NOT NULL,
"status" character varying(255) NOT NULL DEFAULT 'PENDING',
"allowance_id" uuid NOT NULL,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_664715670e1e72c64ce65a078de" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "allowances" ADD CONSTRAINT "FK_80b144a74e630ed63311e97427b" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "allowances" ADD CONSTRAINT "FK_61e6e612f6d4644f8910d453cc9" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "allowance_change_requests" ADD CONSTRAINT "FK_4ea6382927f50cb93873fae16d2" FOREIGN KEY ("allowance_id") REFERENCES "allowances"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "allowance_change_requests" DROP CONSTRAINT "FK_4ea6382927f50cb93873fae16d2"`);
await queryRunner.query(`ALTER TABLE "allowances" DROP CONSTRAINT "FK_61e6e612f6d4644f8910d453cc9"`);
await queryRunner.query(`ALTER TABLE "allowances" DROP CONSTRAINT "FK_80b144a74e630ed63311e97427b"`);
await queryRunner.query(`DROP TABLE "allowance_change_requests"`);
await queryRunner.query(`DROP TABLE "allowances"`);
}
}

View File

@ -1,66 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateGiftEntities1734861516657 implements MigrationInterface {
name = 'CreateGiftEntities1734861516657';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "gift_replies"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"status" character varying NOT NULL DEFAULT 'PENDING',
"color" character varying NOT NULL,
"gift_id" uuid NOT NULL,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "REL_8292da97f1ceb9a806b8bc812f" UNIQUE ("gift_id"),
CONSTRAINT "PK_ec6567bb5ab318bb292fa6599a2" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "gift"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" character varying(255) NOT NULL,
"description" text NOT NULL,
"color" character varying NOT NULL,
"amount" numeric(10,3) NOT NULL,
"status" character varying NOT NULL DEFAULT 'AVAILABLE',
"redeemed_at" TIMESTAMP WITH TIME ZONE,
"giver_id" uuid NOT NULL, "image_id" uuid NOT NULL,
"recipient_id" uuid NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_f91217caddc01a085837ebe0606" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TABLE "gift_redemptions"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"gift_id" uuid NOT NULL,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_6ad7ac76169c3a224ce4a3afff4" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "gift_replies" ADD CONSTRAINT "FK_8292da97f1ceb9a806b8bc812f2" FOREIGN KEY ("gift_id") REFERENCES "gift"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift" ADD CONSTRAINT "FK_0d317b68508819308455db9b9be" FOREIGN KEY ("giver_id") REFERENCES "guardians"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift" ADD CONSTRAINT "FK_4a46b5734fb573dc956904c18d0" FOREIGN KEY ("recipient_id") REFERENCES "juniors"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift" ADD CONSTRAINT "FK_83bb54c127d0e6ee487b90e2996" FOREIGN KEY ("image_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "gift_redemptions" ADD CONSTRAINT "FK_243c4349f0c45ce5385ac316aaa" FOREIGN KEY ("gift_id") REFERENCES "gift"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "gift_redemptions" DROP CONSTRAINT "FK_243c4349f0c45ce5385ac316aaa"`);
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_83bb54c127d0e6ee487b90e2996"`);
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_4a46b5734fb573dc956904c18d0"`);
await queryRunner.query(`ALTER TABLE "gift" DROP CONSTRAINT "FK_0d317b68508819308455db9b9be"`);
await queryRunner.query(`ALTER TABLE "gift_replies" DROP CONSTRAINT "FK_8292da97f1ceb9a806b8bc812f2"`);
await queryRunner.query(`DROP TABLE "gift_redemptions"`);
await queryRunner.query(`DROP TABLE "gift"`);
await queryRunner.query(`DROP TABLE "gift_replies"`);
}
}

View File

@ -1,32 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateNotificationEntityAndEditDevice1734944692999 implements MigrationInterface {
name = 'CreateNotificationEntityAndEditDevice1734944692999';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "notifications"
("id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"title" character varying NOT NULL,
"message" character varying NOT NULL,
"recipient" character varying,
"scope" character varying NOT NULL,
"status" character varying,
"channel" character varying NOT NULL,
"user_id" uuid,
"created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "PK_6a72c3c0f683f6462415e653c3a" PRIMARY KEY ("id"))`,
);
await queryRunner.query(`ALTER TABLE "devices" ADD "fcm_token" character varying`);
await queryRunner.query(
`ALTER TABLE "notifications" ADD CONSTRAINT "FK_9a8a82462cab47c73d25f49261f" 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 "notifications" DROP CONSTRAINT "FK_9a8a82462cab47c73d25f49261f"`);
await queryRunner.query(`ALTER TABLE "devices" DROP COLUMN "fcm_token"`);
await queryRunner.query(`DROP TABLE "notifications"`);
}
}

View File

@ -1,19 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddFlagsToUserEntity1736414850257 implements MigrationInterface {
name = 'AddFlagsToUserEntity1736414850257';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "users" ADD "is_phone_verified" boolean NOT NULL DEFAULT false`);
await queryRunner.query(`ALTER TABLE "users" ADD "is_email_verified" boolean NOT NULL DEFAULT false`);
await queryRunner.query(`ALTER TABLE "users" ALTER COLUMN "phone_number" DROP NOT NULL`);
await queryRunner.query(`ALTER TABLE "users" ALTER COLUMN "country_code" DROP NOT NULL`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "users" ALTER COLUMN "country_code" SET NOT NULL`);
await queryRunner.query(`ALTER TABLE "users" ALTER COLUMN "phone_number" SET NOT NULL`);
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "is_email_verified"`);
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "is_phone_verified"`);
}
}

View File

@ -1,17 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddCreatedByToDocumentTable1736753223884 implements MigrationInterface {
name = 'AddCreatedByToDocumentTable1736753223884';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "documents" ADD "created_by_id" uuid `);
await queryRunner.query(
`ALTER TABLE "documents" ADD CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "documents" DROP CONSTRAINT "FK_7f46f4f77acde1dcedba64cb220"`);
await queryRunner.query(`ALTER TABLE "documents" DROP COLUMN "created_by_id"`);
}
}

View File

@ -1,15 +0,0 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddKycStatusToCustomer1739868002943 implements MigrationInterface {
name = 'AddKycStatusToCustomer1739868002943';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "customers" ADD "kyc_status" character varying(255) NOT NULL DEFAULT 'PENDING'`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "kyc_status"`);
}
}

View File

@ -1,42 +0,0 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class AddCivilidToCustomersAndUpdateNotificationsSettings1739954239949 implements MigrationInterface {
name = 'AddCivilidToCustomersAndUpdateNotificationsSettings1739954239949'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_4662c4433223c01fe69fc1382f5"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "FK_6a72e1a5758643737cc563b96c7"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "REL_6a72e1a5758643737cc563b96c"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP COLUMN "civil_id_front_id"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP CONSTRAINT "REL_4662c4433223c01fe69fc1382f"`);
await queryRunner.query(`ALTER TABLE "juniors" DROP COLUMN "civil_id_back_id"`);
await queryRunner.query(`ALTER TABLE "customers" ADD "civil_id_front_id" uuid NOT NULL`);
await queryRunner.query(`ALTER TABLE "customers" ADD CONSTRAINT "UQ_d5f99c497892ce31598ba19a72c" UNIQUE ("civil_id_front_id")`);
await queryRunner.query(`ALTER TABLE "customers" ADD "civil_id_back_id" uuid NOT NULL`);
await queryRunner.query(`ALTER TABLE "customers" ADD CONSTRAINT "UQ_2191662d124c56dd968ba01bf18" UNIQUE ("civil_id_back_id")`);
await queryRunner.query(`ALTER TABLE "users" ADD "is_email_enabled" boolean NOT NULL DEFAULT false`);
await queryRunner.query(`ALTER TABLE "users" ADD "is_push_enabled" boolean NOT NULL DEFAULT false`);
await queryRunner.query(`ALTER TABLE "users" ADD "is_sms_enabled" boolean NOT NULL DEFAULT false`);
await queryRunner.query(`ALTER TABLE "customers" ADD CONSTRAINT "FK_d5f99c497892ce31598ba19a72c" FOREIGN KEY ("civil_id_front_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "customers" ADD CONSTRAINT "FK_2191662d124c56dd968ba01bf18" FOREIGN KEY ("civil_id_back_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_2191662d124c56dd968ba01bf18"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "FK_d5f99c497892ce31598ba19a72c"`);
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "is_sms_enabled"`);
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "is_push_enabled"`);
await queryRunner.query(`ALTER TABLE "users" DROP COLUMN "is_email_enabled"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "UQ_2191662d124c56dd968ba01bf18"`);
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "civil_id_back_id"`);
await queryRunner.query(`ALTER TABLE "customers" DROP CONSTRAINT "UQ_d5f99c497892ce31598ba19a72c"`);
await queryRunner.query(`ALTER TABLE "customers" DROP COLUMN "civil_id_front_id"`);
await queryRunner.query(`ALTER TABLE "juniors" ADD "civil_id_back_id" uuid NOT NULL`);
await queryRunner.query(`ALTER TABLE "juniors" ADD CONSTRAINT "REL_4662c4433223c01fe69fc1382f" UNIQUE ("civil_id_back_id")`);
await queryRunner.query(`ALTER TABLE "juniors" ADD "civil_id_front_id" uuid NOT NULL`);
await queryRunner.query(`ALTER TABLE "juniors" ADD CONSTRAINT "REL_6a72e1a5758643737cc563b96c" UNIQUE ("civil_id_front_id")`);
await queryRunner.query(`ALTER TABLE "juniors" ADD CONSTRAINT "FK_6a72e1a5758643737cc563b96c7" FOREIGN KEY ("civil_id_front_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "juniors" ADD CONSTRAINT "FK_4662c4433223c01fe69fc1382f5" FOREIGN KEY ("civil_id_back_id") REFERENCES "documents"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
}
}

View File

@ -1,20 +0,0 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class CreateUserRegistrationTable1740045960580 implements MigrationInterface {
name = 'CreateUserRegistrationTable1740045960580'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "user_registration_tokens" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "token" character varying(255) NOT NULL, "user_type" character varying(255) NOT NULL, "is_used" boolean NOT NULL DEFAULT false, "expiry_date" TIMESTAMP NOT NULL, "user_id" uuid, "junior_id" uuid, "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "created_at" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "UQ_5881556d05b46fc7bd9e3bba935" UNIQUE ("token"), CONSTRAINT "PK_135a2d86443071ff0ba1c14135c" PRIMARY KEY ("id"))`);
await queryRunner.query(`CREATE INDEX "IDX_5881556d05b46fc7bd9e3bba93" ON "user_registration_tokens" ("token") `);
await queryRunner.query(`ALTER TABLE "user_registration_tokens" ADD CONSTRAINT "FK_57cbbe079a7945d6ed1df114825" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
await queryRunner.query(`ALTER TABLE "user_registration_tokens" ADD CONSTRAINT "FK_e41bec3ed6e549cbf90f57cc344" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "user_registration_tokens" DROP CONSTRAINT "FK_e41bec3ed6e549cbf90f57cc344"`);
await queryRunner.query(`ALTER TABLE "user_registration_tokens" DROP CONSTRAINT "FK_57cbbe079a7945d6ed1df114825"`);
await queryRunner.query(`DROP INDEX "public"."IDX_5881556d05b46fc7bd9e3bba93"`);
await queryRunner.query(`DROP TABLE "user_registration_tokens"`);
}
}

View File

@ -58,7 +58,7 @@ const DEFAULT_AVATARS = [
documentType: DocumentType.DEFAULT_AVATAR,
},
];
export class SeedDefaultAvatar1733750228289 implements MigrationInterface {
export class SeedDefaultAvatar1753869637732 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.manager.getRepository(Document).save(DEFAULT_AVATARS);
}

View File

@ -1,24 +1,4 @@
export * from './1732434281561-create-document-entity';
export * from './1733206728721-create-user-entity';
export * from './1733209041336-create-otp-entity';
export * from './1733298524771-create-customer-entity';
export * from './1733314952318-create-device-entity';
export * from './1733731507261-create-junior-entity';
export * from './1733732021622-create-guardian-entity';
export * from './1733748083604-create-theme-entity';
export * from './1733750228289-seed-default-avatar';
export * from './1733904556416-create-task-entities';
export * from './1753869637732-seed-default-avatar';
export * from './1733990253208-seeds-default-tasks-logo';
export * from './1733993920226-create-customer-notifications-settings-table';
export * from './1734246386471-create-saving-goals-entities';
export * from './1734247702310-seeds-goals-categories';
export * from './1734262619426-create-junior-registration-token-table';
export * from './1734503895302-create-money-request-entity';
export * from './1734601976591-create-allowance-entities';
export * from './1734861516657-create-gift-entities';
export * from './1734944692999-create-notification-entity-and-edit-device';
export * from './1736414850257-add-flags-to-user-entity';
export * from './1736753223884-add_created_by_to_document_table';
export * from './1739868002943-add-kyc-status-to-customer';
export * from './1739954239949-add-civilid-to-customers-and-update-notifications-settings';
export * from './1740045960580-create-user-registration-table';
export * from './1733750228289-initial-migration';

View File

@ -2,10 +2,10 @@ import { DocumentType } from '../enums';
export const BUCKETS: Record<DocumentType, string> = {
[DocumentType.PROFILE_PICTURE]: 'profile-pictures',
[DocumentType.PASSPORT]: 'passports',
[DocumentType.DEFAULT_AVATAR]: 'avatars',
[DocumentType.DEFAULT_TASKS_LOGO]: 'tasks-logo',
[DocumentType.CUSTOM_AVATAR]: 'avatars',
[DocumentType.CUSTOM_TASKS_LOGO]: 'tasks-logo',
[DocumentType.GOALS]: 'goals',
[DocumentType.IDENTIFICATION_CARD]: 'identification-cards',
};

View File

@ -1,6 +1,6 @@
export enum DocumentType {
PROFILE_PICTURE = 'PROFILE_PICTURE',
PASSPORT = 'PASSPORT',
IDENTIFICATION_CARD = 'IDENTIFICATION_CARD',
DEFAULT_AVATAR = 'DEFAULT_AVATAR',
DEFAULT_TASKS_LOGO = 'DEFAULT_TASKS_LOGO',
CUSTOM_AVATAR = 'CUSTOM_AVATAR',

View File

@ -10,11 +10,13 @@
"INVALID_BIOMETRIC": "البيانات البيومترية المقدمة غير صالحة. يرجى المحاولة مرة أخرى أو إعادة إعداد المصادقة البيومترية.",
"PASSWORD_MISMATCH": "كلمات المرور التي أدخلتها غير متطابقة. يرجى إدخال كلمات المرور مرة أخرى.",
"INVALID_PASSCODE": "رمز المرور الذي أدخلته غير صحيح. يرجى المحاولة مرة أخرى.",
"PASSCODE_ALREADY_SET": "تم تعيين رمز المرور بالفعل."
"PASSCODE_ALREADY_SET": "تم تعيين رمز المرور بالفعل.",
"APPLE_RE-CONSENT_REQUIRED": "إعادة الموافقة على آبل مطلوبة. يرجى إلغاء تطبيقك من إعدادات معرف آبل الخاصة بك والمحاولة مرة أخرى."
},
"USER": {
"PHONE_ALREADY_VERIFIED": "تم التحقق من رقم الهاتف بالفعل.",
"EMAIL_ALREADY_VERIFIED": "تم التحقق من عنوان البريد الإلكتروني بالفعل.",
"EMAIL_ALREADY_SET": "تم تعيين عنوان البريد الإلكتروني بالفعل.",
"EMAIL_ALREADY_TAKEN": "عنوان البريد الإلكتروني مستخدم بالفعل. يرجى تجربة عنوان بريد إلكتروني آخر.",
"PHONE_NUMBER_ALREADY_SET": "تم تعيين رقم الهاتف بالفعل.",
@ -40,7 +42,8 @@
"ALREADY_REJECTED": "تم رفض طلب تغيير المصروف بالفعل."
},
"CUSTOMER": {
"NOT_FOUND": "لم يتم العثور على العميل."
"NOT_FOUND": "لم يتم العثور على العميل.",
"ALREADY_EXISTS": "العميل موجود بالفعل."
},
"GIFT": {

View File

@ -16,6 +16,7 @@
"otp": "رمز التحقق",
"grantType": "نوع الإذن",
"signature": "التوقيع",
"appleToken": "رمز أبل",
"googleToken": "رمز جوجل",
"fcmToken": "رمز FCM",
"refreshToken": "رمز التحديث",

View File

@ -10,11 +10,13 @@
"INVALID_BIOMETRIC": "The biometric data provided is invalid. Please try again or reconfigure your biometric settings.",
"PASSWORD_MISMATCH": "The passwords you entered do not match. Please re-enter the passwords.",
"INVALID_PASSCODE": "The passcode you entered is incorrect. Please try again.",
"PASSCODE_ALREADY_SET": "The pass code has already been set."
"PASSCODE_ALREADY_SET": "The pass code has already been set.",
"APPLE_RE-CONSENT_REQUIRED": "Apple re-consent is required. Please revoke the app from your Apple ID settings and try again."
},
"USER": {
"PHONE_ALREADY_VERIFIED": "The phone number has already been verified.",
"EMAIL_ALREADY_VERIFIED": "The email address has already been verified.",
"EMAIL_ALREADY_SET": "The email address has already been set.",
"EMAIL_ALREADY_TAKEN": "The email address is already in use. Please try another email address.",
"PHONE_NUMBER_ALREADY_SET": "The phone number has already been set.",
@ -39,7 +41,8 @@
"ALREADY_REJECTED": "The allowance change request has already been rejected."
},
"CUSTOMER": {
"NOT_FOUND": "The customer was not found."
"NOT_FOUND": "The customer was not found.",
"ALREADY_EXISTS": "The customer already exists."
},
"GIFT": {

View File

@ -17,11 +17,15 @@
"otp": "OTP",
"grantType": "Grant type",
"signature": "Signature",
"appleToken": "Apple token",
"googleToken": "Google token",
"fcmToken": "FCM token",
"refreshToken": "Refresh token",
"qrToken": "QR token",
"passcode": "Passcode"
"passcode": "Passcode",
"apple": {
"additionalData": "Additional data"
}
},
"customer": {

View File

@ -1,5 +1,5 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsDateString, IsEmail, IsEnum, IsNotEmpty, IsString, IsUUID, Matches } from 'class-validator';
import { IsDateString, IsEmail, IsEnum, IsNotEmpty, IsOptional, IsString, IsUUID, Matches } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { COUNTRY_CODE_REGEX } from '~/auth/constants';
import { IsValidPhoneNumber } from '~/core/decorators/validations';
@ -10,12 +10,14 @@ export class CreateJuniorRequestDto {
@Matches(COUNTRY_CODE_REGEX, {
message: i18n('validation.Matches', { path: 'general', property: 'auth.countryCode' }),
})
@IsOptional()
countryCode: string = '+966';
@ApiProperty({ example: '787259134' })
@IsValidPhoneNumber({
message: i18n('validation.IsValidPhoneNumber', { path: 'general', property: 'auth.phoneNumber' }),
})
@IsOptional()
phoneNumber!: string;
@ApiProperty({ example: 'John' })
@ -51,4 +53,9 @@ export class CreateJuniorRequestDto {
@ApiProperty({ example: 'bf342-3f3f-3f3f-3f3f' })
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'junior.civilIdBackId' }) })
civilIdBackId!: string;
@ApiProperty({ example: '123e4567-e89b-12d3-a456-426614174000' })
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'customer.profilePictureId' }) })
@IsOptional()
profilePictureId!: string;
}

View File

@ -1,9 +1,11 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { FindOptionsWhere } from 'typeorm';
import { Transactional } from 'typeorm-transactional';
import { Roles } from '~/auth/enums';
import { PageOptionsRequestDto } from '~/core/dtos';
import { CustomerService } from '~/customer/services';
import { DocumentService, OciService } from '~/document/services';
import { User } from '~/user/entities';
import { UserType } from '~/user/enums';
import { UserService } from '~/user/services';
import { UserTokenService } from '~/user/services/user-token.service';
@ -28,10 +30,17 @@ export class JuniorService {
@Transactional()
async createJuniors(body: CreateJuniorRequestDto, guardianId: string) {
this.logger.log(`Creating junior for guardian ${guardianId}`);
const existingUser = await this.userService.findUser([
{ email: body.email },
{ phoneNumber: body.phoneNumber, countryCode: body.countryCode },
]);
const searchConditions: FindOptionsWhere<User>[] = [{ email: body.email }];
if (body.phoneNumber && body.countryCode) {
searchConditions.push({
phoneNumber: body.phoneNumber,
countryCode: body.countryCode,
});
}
const existingUser = await this.userService.findUser(searchConditions);
if (existingUser) {
this.logger.error(`User with email ${body.email} or phone number ${body.phoneNumber} already exists`);

View File

@ -11,8 +11,7 @@ export class UserRepository {
createUnverifiedUser(data: Partial<User>) {
return this.userRepository.save(
this.userRepository.create({
phoneNumber: data.phoneNumber,
countryCode: data.countryCode,
email: data.email,
roles: data.roles,
}),
);

View File

@ -4,8 +4,10 @@ import * as bcrypt from 'bcrypt';
import moment from 'moment';
import { FindOptionsWhere } from 'typeorm';
import { Transactional } from 'typeorm-transactional';
import { CountryIso } from '~/common/enums';
import { NotificationsService } from '~/common/modules/notification/services';
import { CreateUnverifiedUserRequestDto } from '../../auth/dtos/request';
import { CustomerService } from '~/customer/services';
import { CreateUnverifiedUserRequestDto, VerifyUserRequestDto } from '../../auth/dtos/request';
import { Roles } from '../../auth/enums';
import {
CreateCheckerRequestDto,
@ -29,6 +31,7 @@ export class UserService {
private readonly deviceService: DeviceService,
private readonly userTokenService: UserTokenService,
private readonly configService: ConfigService,
private customerService: CustomerService,
) {}
findUser(where: FindOptionsWhere<User> | FindOptionsWhere<User>[]) {
@ -51,9 +54,18 @@ export class UserService {
return this.userRepository.update(userId, { phoneNumber, countryCode });
}
verifyPhoneNumber(userId: string) {
this.logger.log(`Verifying phone number for user ${userId}`);
return this.userRepository.update(userId, { isPhoneVerified: true });
@Transactional()
async verifyUser(userId: string, body: VerifyUserRequestDto) {
this.logger.log(`Verifying user email with id ${userId}`);
await Promise.all([
this.customerService.createGuardianCustomer(userId, {
firstName: body.firstName,
lastName: body.lastName,
dateOfBirth: body.dateOfBirth,
countryOfResidence: body.countryOfResidence,
}),
this.userRepository.update(userId, { isEmailVerified: true }),
]);
}
findUsers(filters: UserFiltersRequestDto) {
@ -74,26 +86,46 @@ export class UserService {
return user;
}
async findOrCreateUser({ phoneNumber, countryCode }: CreateUnverifiedUserRequestDto) {
this.logger.log(`Finding or creating user with phone number ${phoneNumber} and country code ${countryCode}`);
const user = await this.userRepository.findOne({ phoneNumber });
@Transactional()
async findOrCreateUser(body: CreateUnverifiedUserRequestDto) {
this.logger.log(`Finding or creating user with email ${body.email}`);
const user = await this.userRepository.findOne({ email: body.email });
if (!user) {
this.logger.log(`User with phone number ${phoneNumber} not found, creating new user`);
return this.userRepository.createUnverifiedUser({ phoneNumber, countryCode, roles: [Roles.GUARDIAN] });
this.logger.log(`User with email ${body.email} not found, creating new user`);
return this.userRepository.createUnverifiedUser({ email: body.email, roles: [Roles.GUARDIAN] });
}
if (user && user.roles.includes(Roles.GUARDIAN) && user.isProfileCompleted) {
this.logger.error(`User with phone number ${phoneNumber} already exists`);
throw new BadRequestException('USER.PHONE_NUMBER_ALREADY_EXISTS');
if (user && user.roles.includes(Roles.GUARDIAN) && user.isEmailVerified) {
this.logger.error(`User with email ${body.email} already exists`);
throw new BadRequestException('USER.EMAIL_ALREADY_TAKEN');
}
if (user && user.roles.includes(Roles.JUNIOR)) {
this.logger.error(`User with phone number ${phoneNumber} is an already registered junior`);
this.logger.error(`User with email ${body.email} is an already registered junior`);
throw new BadRequestException('USER.JUNIOR_UPGRADE_NOT_SUPPORTED_YET');
//TODO add role Guardian to the existing user and send OTP
}
this.logger.log(`User with phone number ${phoneNumber} and country code ${countryCode} found successfully`);
this.logger.log(`User with email ${body.email}`);
return user;
}
async findOrCreateByEmail(email: string) {
this.logger.log(`Finding or creating user with email ${email} `);
const user = await this.userRepository.findOne({ email });
if (!user) {
this.logger.log(`User with email ${email} not found, creating new user`);
return this.userRepository.createUser({ email, roles: [Roles.GUARDIAN] });
}
if (user && user.roles.includes(Roles.JUNIOR)) {
this.logger.error(`User with email ${email} is an already registered junior`);
throw new BadRequestException('USER.JUNIOR_UPGRADE_NOT_SUPPORTED_YET');
//TODO add role Guardian to the existing user and send OTP
}
this.logger.log(`User with email ${email} found successfully`);
return user;
}
@ -149,7 +181,7 @@ export class UserService {
});
}
async createGoogleUser(googleId: string, email: string) {
async createGoogleUser(googleId: string, email: string, firstName: string, lastName: string) {
this.logger.log(`Creating google user with googleId ${googleId} and email ${email}`);
const user = await this.userRepository.createUser({
googleId,
@ -158,10 +190,16 @@ export class UserService {
isEmailVerified: true,
});
await this.customerService.createGuardianCustomer(user.id, {
firstName,
lastName,
countryOfResidence: CountryIso.SAUDI_ARABIA,
});
return this.findUserOrThrow({ id: user.id });
}
async createAppleUser(appleId: string, email: string) {
async createAppleUser(appleId: string, email: string, firstName: string, lastName: string) {
this.logger.log(`Creating apple user with appleId ${appleId} and email ${email}`);
const user = await this.userRepository.createUser({
appleId,
@ -170,6 +208,11 @@ export class UserService {
isEmailVerified: true,
});
await this.customerService.createGuardianCustomer(user.id, {
firstName,
lastName,
countryOfResidence: CountryIso.SAUDI_ARABIA,
});
return this.findUserOrThrow({ id: user.id });
}
@ -182,6 +225,15 @@ export class UserService {
return this.userRepository.update(userId, { password: hashedPasscode, salt, isProfileCompleted: true });
}
async updateUser(userId: string, data: Partial<User>) {
this.logger.log(`Updating user ${userId} with data ${JSON.stringify(data)}`);
const { affected } = await this.userRepository.update(userId, data);
if (affected === 0) {
this.logger.error(`User with id ${userId} not found`);
throw new BadRequestException('USER.NOT_FOUND');
}
}
private sendCheckerAccountCreatedEmail(email: string, token: string) {
return this.notificationsService.sendEmailAsync({
to: email,

View File

@ -1,13 +1,18 @@
import { forwardRef, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { NotificationModule } from '~/common/modules/notification/notification.module';
import { CustomerModule } from '~/customer/customer.module';
import { AdminUserController, UserController } from './controllers';
import { Device, User, UserRegistrationToken } from './entities';
import { DeviceRepository, UserRepository, UserTokenRepository } from './repositories';
import { DeviceService, UserService, UserTokenService } from './services';
@Module({
imports: [TypeOrmModule.forFeature([User, Device, UserRegistrationToken]), forwardRef(() => NotificationModule)],
imports: [
TypeOrmModule.forFeature([User, Device, UserRegistrationToken]),
forwardRef(() => NotificationModule),
forwardRef(() => CustomerModule),
],
providers: [UserService, DeviceService, UserRepository, DeviceRepository, UserTokenRepository, UserTokenService],
exports: [UserService, DeviceService, UserTokenService],
controllers: [UserController, AdminUserController],