Compare commits

...

20 Commits

Author SHA1 Message Date
872d231f72 feat: show embossing information for child cards 2025-09-09 21:45:37 +03:00
cc4c8254f6 feat: view child active cards 2025-09-09 21:37:55 +03:00
039c95aa56 fix: calculating child and parent balance 2025-09-09 20:31:48 +03:00
e1f50decfa feat: money requests 2025-09-08 21:38:11 +03:00
e6642b5a15 fix: fix controller name 2025-09-07 21:47:17 +03:00
954aa422a2 fix: fix mock request for funding decorators 2025-09-07 21:40:55 +03:00
15a48e4884 fix: validate card spending limit before transfering to child 2025-09-07 21:18:49 +03:00
d768da70f2 feat: transfer to parent 2025-09-07 20:23:11 +03:00
9b0e1791da feat: transfer money to child 2025-09-07 20:14:28 +03:00
44b5937f7a feat: finalize update junior 2025-09-07 18:13:28 +03:00
edddc2f457 feat: update junior 2025-09-07 09:12:14 +03:00
88730a2b2b fix: fix create application mock 2025-08-26 19:17:00 +03:00
3df34c0017 fix: fix duplicate iban 2025-08-26 12:19:47 +03:00
7dd309e0e3 fix: fix null assertion in creating junior 2025-08-24 20:14:59 +03:00
4552a7fc93 fix: fix issue with customer relationship in creating junior 2025-08-24 20:12:57 +03:00
740135051d feat: create card for children 2025-08-24 20:01:07 +03:00
3222aa4a66 fix: fix card embossing info endpoint 2025-08-24 18:40:49 +03:00
6602414779 feat: finialize creating juniors 2025-08-23 21:52:59 +03:00
7291447c5a Merge branch 'dev' into feat/neoleap-integration 2025-08-23 20:12:48 +03:00
d437b21dc3 fix: make kyc run on mocks 2025-08-23 19:30:29 +03:00
69 changed files with 7974 additions and 3295 deletions

9001
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -28,6 +28,7 @@ import { HealthModule } from './health/health.module';
import { JuniorModule } from './junior/junior.module';
import { UserModule } from './user/user.module';
import { WebhookModule } from './webhook/webhook.module';
import { MoneyRequestModule } from './money-request/money-request.module';
@Module({
controllers: [],
@ -74,6 +75,7 @@ import { WebhookModule } from './webhook/webhook.module';
CronModule,
NeoLeapModule,
WebhookModule,
MoneyRequestModule,
],
providers: [
// Global Pipes

View File

@ -9,9 +9,11 @@ import {
ChangePasswordRequestDto,
CreateUnverifiedUserRequestDto,
ForgetPasswordRequestDto,
JuniorLoginRequestDto,
LoginRequestDto,
RefreshTokenRequestDto,
SendForgetPasswordOtpRequestDto,
setJuniorPasswordRequestDto,
VerifyForgetPasswordOtpRequestDto,
VerifyUserRequestDto,
} from '../dtos/request';
@ -69,10 +71,26 @@ export class AuthController {
@Post('change-password')
@HttpCode(HttpStatus.NO_CONTENT)
@UseGuards(AccessTokenGuard)
async changePassword(@AuthenticatedUser() { sub }: IJwtPayload, @Body() forgetPasswordDto: ChangePasswordRequestDto) {
changePassword(@AuthenticatedUser() { sub }: IJwtPayload, @Body() forgetPasswordDto: ChangePasswordRequestDto) {
return this.authService.changePassword(sub, forgetPasswordDto);
}
@Post('junior/set-password')
@HttpCode(HttpStatus.NO_CONTENT)
@Public()
setJuniorPasscode(@Body() setPassworddto: setJuniorPasswordRequestDto) {
return this.authService.setJuniorPassword(setPassworddto);
}
@Post('junior/login')
@HttpCode(HttpStatus.OK)
@ApiDataResponse(LoginResponseDto)
async juniorLogin(@Body() juniorLoginDto: JuniorLoginRequestDto) {
const [res, user] = await this.authService.juniorLogin(juniorLoginDto);
return ResponseFactory.data(new LoginResponseDto(res, user));
}
@Post('refresh-token')
@Public()
async refreshToken(@Body() { refreshToken }: RefreshTokenRequestDto) {

View File

@ -1,11 +1,11 @@
export * from './change-password.request.dto';
export * from './create-unverified-user.request.dto';
export * from './forget-password.request.dto';
export * from './junior-login.request.dto';
export * from './login.request.dto';
export * from './refresh-token.request.dto';
export * from './send-forget-password-otp.request.dto';
export * from './set-junior-password.request.dto';
export * from './set-passcode.request.dto';
export * from './verify-forget-password-otp.request.dto';
export * from './verify-otp.request.dto';
export * from './verify-user.request.dto';

View File

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

View File

@ -1,8 +1,11 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, PickType } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { SetPasscodeRequestDto } from './set-passcode.request.dto';
export class setJuniorPasswordRequestDto extends SetPasscodeRequestDto {
import { ChangePasswordRequestDto } from './change-password.request.dto';
export class setJuniorPasswordRequestDto extends PickType(ChangePasswordRequestDto, [
'newPassword',
'confirmNewPassword',
]) {
@ApiProperty()
@IsString({ message: i18n('validation.IsNumberString', { path: 'general', property: 'auth.qrToken' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'auth.qrToken' }) })

View File

@ -1,15 +0,0 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNumberString, MaxLength, MinLength } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
const PASSCODE_LENGTH = 6;
export class SetPasscodeRequestDto {
@ApiProperty({ example: '123456' })
@IsNumberString(
{ no_symbols: true },
{ message: i18n('validation.IsNumberString', { path: 'general', property: 'auth.passcode' }) },
)
@MinLength(PASSCODE_LENGTH, { message: i18n('validation.MinLength', { path: 'general', property: 'auth.passcode' }) })
@MaxLength(PASSCODE_LENGTH, { message: i18n('validation.MaxLength', { path: 'general', property: 'auth.passcode' }) })
passcode!: string;
}

View File

@ -14,6 +14,7 @@ import {
ChangePasswordRequestDto,
CreateUnverifiedUserRequestDto,
ForgetPasswordRequestDto,
JuniorLoginRequestDto,
LoginRequestDto,
SendForgetPasswordOtpRequestDto,
setJuniorPasswordRequestDto,
@ -196,11 +197,14 @@ export class AuthService {
this.logger.log(`Password changed successfully for user with id ${userId}`);
}
async setJuniorPasscode(body: setJuniorPasswordRequestDto) {
async setJuniorPassword(body: setJuniorPasswordRequestDto) {
this.logger.log(`Setting passcode for junior with qrToken ${body.qrToken}`);
if (body.newPassword != body.confirmNewPassword) {
throw new BadRequestException('AUTH.PASSWORD_MISMATCH');
}
const juniorId = await this.userTokenService.validateToken(body.qrToken, UserType.JUNIOR);
const salt = bcrypt.genSaltSync(SALT_ROUNDS);
const hashedPasscode = bcrypt.hashSync(body.passcode, salt);
const hashedPasscode = bcrypt.hashSync(body.newPassword, salt);
await this.userService.setPassword(juniorId!, hashedPasscode, salt);
await this.userTokenService.invalidateToken(body.qrToken);
this.logger.log(`Passcode set successfully for junior with id ${juniorId}`);
@ -278,6 +282,26 @@ export class AuthService {
return [tokens, user];
}
async juniorLogin(juniorLoginDto: JuniorLoginRequestDto): Promise<[ILoginResponse, User]> {
const user = await this.userService.findUser({ email: juniorLoginDto.email });
if (!user || !user.roles.includes(Roles.JUNIOR)) {
throw new UnauthorizedException('AUTH.INVALID_CREDENTIALS');
}
this.logger.log(`validating password for user with email ${juniorLoginDto.email}`);
const isPasswordValid = bcrypt.compareSync(juniorLoginDto.password, user.password);
if (!isPasswordValid) {
this.logger.error(`Invalid password for user with email ${juniorLoginDto.email}`);
throw new UnauthorizedException('AUTH.INVALID_CREDENTIALS');
}
const tokens = await this.generateAuthToken(user);
this.logger.log(`Password validated successfully for user`);
return [tokens, user];
}
private async generateAuthToken(user: User) {
this.logger.log(`Generating auth token for user with id ${user.id}`);
const [accessToken, refreshToken] = await Promise.all([

View File

@ -1,12 +1,14 @@
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Post, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Roles } from '~/auth/enums';
import { IJwtPayload } from '~/auth/interfaces';
import { AuthenticatedUser } from '~/common/decorators';
import { AccessTokenGuard } from '~/common/guards';
import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
import { AccessTokenGuard, RolesGuard } from '~/common/guards';
import { CardEmbossingDetailsResponseDto } from '~/common/modules/neoleap/dtos/response';
import { ApiDataResponse } from '~/core/decorators';
import { ResponseFactory } from '~/core/utils';
import { CardResponseDto } from '../dtos/responses';
import { FundIbanRequestDto } from '../dtos/requests';
import { AccountIbanResponseDto, CardResponseDto, ChildCardResponseDto } from '../dtos/responses';
import { CardService } from '../services';
@Controller('cards')
@ -23,6 +25,24 @@ export class CardsController {
return ResponseFactory.data(new CardResponseDto(card));
}
@Get('child-cards')
@UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(ChildCardResponseDto)
async getChildCards(@AuthenticatedUser() { sub }: IJwtPayload) {
const cards = await this.cardService.getChildCards(sub);
return ResponseFactory.data(cards.map((card) => new ChildCardResponseDto(card)));
}
@Get('child-cards/:cardid/embossing-details')
@UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(CardEmbossingDetailsResponseDto)
async getChildCardEmbossingDetails(@Param('cardid') cardId: string, @AuthenticatedUser() { sub }: IJwtPayload) {
const res = await this.cardService.getChildCardEmbossingInformation(cardId, sub);
return ResponseFactory.data(res);
}
@Get('current')
@ApiDataResponse(CardResponseDto)
async getCurrentCard(@AuthenticatedUser() { sub }: IJwtPayload) {
@ -36,4 +56,22 @@ export class CardsController {
const res = await this.cardService.getEmbossingInformation(sub);
return ResponseFactory.data(res);
}
@Get('iban')
@UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(AccountIbanResponseDto)
async getCardIban(@AuthenticatedUser() { sub }: IJwtPayload) {
const iban = await this.cardService.getIbanInformation(sub);
return ResponseFactory.data(new AccountIbanResponseDto(iban));
}
@Post('mock/fund-iban')
@ApiOperation({ summary: 'Mock endpoint to fund the IBAN - For testing purposes only' })
@UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@HttpCode(HttpStatus.NO_CONTENT)
fundIban(@Body() { amount, iban }: FundIbanRequestDto) {
return this.cardService.fundIban(iban, amount);
}
}

View File

@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString } from 'class-validator';
import { TransferToJuniorRequestDto } from '~/junior/dtos/request';
export class FundIbanRequestDto extends TransferToJuniorRequestDto {
@ApiProperty({ example: 'DE89370400440532013000' })
@IsString()
iban!: string;
}

View File

@ -0,0 +1 @@
export * from './fund-iban.request.dto';

View File

@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
export class AccountIbanResponseDto {
@ApiProperty({ example: 'DE89370400440532013000' })
iban!: string;
constructor(iban: string) {
this.iban = iban;
}
}

View File

@ -43,6 +43,13 @@ export class CardResponseDto {
})
balance!: number;
@ApiProperty({
example: 100.0,
nullable: true,
description: 'The reserved balance of the card (applicable for child accounts).',
})
reservedBalance!: number | null;
constructor(card: Card) {
this.id = card.id;
this.firstSixDigits = card.firstSixDigits;
@ -52,5 +59,6 @@ export class CardResponseDto {
this.statusDescription = CardStatusDescriptionMapper[card.statusDescription][UserLocale.ENGLISH].description;
this.balance =
card.customerType === CustomerType.CHILD ? Math.min(card.limit, card.account.balance) : card.account.balance;
this.reservedBalance = card.customerType === CustomerType.PARENT ? card.account.reservedBalance : null;
}
}

View File

@ -0,0 +1,48 @@
import { ApiProperty } from '@nestjs/swagger';
import { Card } from '~/card/entities';
import { Gender } from '~/customer/enums';
import { DocumentMetaResponseDto } from '~/document/dtos/response';
import { CardResponseDto } from './card.response.dto';
class JuniorInfo {
@ApiProperty({ example: 'id' })
id!: string;
@ApiProperty({ example: 'FirstName' })
firstName!: string;
@ApiProperty({ example: 'LastName' })
lastName!: string;
@ApiProperty({ example: 'test@example.com' })
email!: string;
@ApiProperty({ enum: Gender, example: Gender.MALE })
gender!: Gender;
@ApiProperty({ example: '2000-01-01' })
dateOfBirth!: Date;
@ApiProperty({ example: DocumentMetaResponseDto, nullable: true })
profilePicture!: DocumentMetaResponseDto | null;
constructor(card: Card) {
this.id = card.customer?.junior?.id;
this.firstName = card.customer?.firstName;
this.lastName = card.customer?.lastName;
this.email = card.customer?.user?.email;
this.gender = card.customer.gender;
this.profilePicture = card.customer?.user?.profilePicture
? new DocumentMetaResponseDto(card.customer.user.profilePicture)
: null;
}
}
export class ChildCardResponseDto extends CardResponseDto {
@ApiProperty({ type: JuniorInfo })
junior!: JuniorInfo | null;
constructor(card: Card) {
super(card);
this.junior = card.customer?.junior ? new JuniorInfo(card) : null;
}
}

View File

@ -1 +1,3 @@
export * from './account-iban.response.dto';
export * from './card.response.dto';
export * from './child-card.response.dto';

View File

@ -25,6 +25,9 @@ export class Account {
@Column('decimal', { precision: 10, scale: 2, default: 0.0, name: 'balance' })
balance!: number;
@Column('decimal', { precision: 10, scale: 2, default: 0.0, name: 'reserved_balance' })
reservedBalance!: number;
@OneToMany(() => Card, (card) => card.account, { cascade: true })
cards!: Card[];

View File

@ -39,7 +39,7 @@ export class Card {
@Column({ type: 'varchar', nullable: false, name: 'customer_type' })
customerType!: CustomerType;
@Column({ type: 'varchar', nullable: false, default: CardColors.BLUE })
@Column({ type: 'varchar', nullable: false, default: CardColors.DEEP_MAGENTA })
color!: CardColors;
@Column({ type: 'varchar', nullable: false, default: CardStatus.PENDING })

View File

@ -1,4 +1,13 @@
export enum CardColors {
RED = 'RED',
BLUE = 'BLUE',
RAINBOW_PASTEL = 'RAINBOW_PASTEL',
DEEP_MAGENTA = 'DEEP_MAGENTA',
GREEN_TEAL = 'GREEN_TEAL',
BLUE_GREEN = 'BLUE_GREEN',
TEAL_NAVY = 'TEAL_NAVY',
PURPLE_PINK = 'PURPLE_PINK',
GOLD_BLUE = 'GOLD_BLUE',
OCEAN_BLUE = 'OCEAN_BLUE',
BROWN_RUST = 'BROWN_RUST',
}

View File

@ -27,6 +27,13 @@ export class AccountRepository {
});
}
getAccountByIban(iban: string): Promise<Account | null> {
return this.accountRepository.findOne({
where: { iban },
relations: ['cards'],
});
}
getAccountByAccountNumber(accountNumber: string): Promise<Account | null> {
return this.accountRepository.findOne({
where: { accountNumber },
@ -34,6 +41,13 @@ export class AccountRepository {
});
}
getAccountByCustomerId(customerId: string): Promise<Account | null> {
return this.accountRepository.findOne({
where: { cards: { customerId } },
relations: ['cards'],
});
}
topUpAccountBalance(accountReference: string, amount: number) {
return this.accountRepository.increment({ accountReference }, 'balance', amount);
}
@ -41,4 +55,12 @@ export class AccountRepository {
decreaseAccountBalance(accountReference: string, amount: number) {
return this.accountRepository.decrement({ accountReference }, 'balance', amount);
}
increaseReservedBalance(accountId: string, amount: number) {
return this.accountRepository.increment({ id: accountId }, 'reservedBalance', amount);
}
decreaseReservedBalance(accountId: string, amount: number) {
return this.accountRepository.decrement({ id: accountId }, 'reservedBalance', amount);
}
}

View File

@ -9,24 +9,38 @@ import { CardColors, CardIssuers, CardScheme, CardStatus, CardStatusDescription,
export class CardRepository {
constructor(@InjectRepository(Card) private readonly cardRepository: Repository<Card>) {}
createCard(customerId: string, accountId: string, card: CreateApplicationResponse): Promise<Card> {
createCard(
customerId: string,
accountId: string,
card: CreateApplicationResponse,
cardColor?: CardColors,
parentId?: string,
): Promise<Card> {
return this.cardRepository.save(
this.cardRepository.create({
customerId: customerId,
expiry: card.expiryDate,
cardReference: card.cardId,
customerType: CustomerType.PARENT,
customerType: parentId ? CustomerType.CHILD : CustomerType.PARENT,
firstSixDigits: card.firstSixDigits,
lastFourDigits: card.lastFourDigits,
color: CardColors.BLUE,
color: cardColor ? cardColor : CardColors.DEEP_MAGENTA,
scheme: CardScheme.VISA,
issuer: CardIssuers.NEOLEAP,
accountId: accountId,
vpan: card.vpan,
parentId,
}),
);
}
findChildCardsForGuardian(guardianId: string): Promise<Card[]> {
return this.cardRepository.find({
where: { parentId: guardianId, customerType: CustomerType.CHILD },
relations: ['account', 'customer', 'customer.user', 'customer.user.profilePicture', 'customer.junior'],
});
}
getCardById(id: string): Promise<Card | null> {
return this.cardRepository.findOne({ where: { id }, relations: ['account'] });
}
@ -55,4 +69,10 @@ export class CardRepository {
statusDescription: statusDescription,
});
}
updateCardLimit(cardId: string, newLimit: number) {
return this.cardRepository.update(cardId, {
limit: newLimit,
});
}
}

View File

@ -57,6 +57,28 @@ export class TransactionRepository {
);
}
createInternalChildTransaction(card: Card, amount: number): Promise<Transaction> {
return this.transactionRepository.save(
this.transactionRepository.create({
transactionId: `CHILD-${card.id}-${Date.now()}`,
transactionAmount: amount,
transactionCurrency: '682',
billingAmount: 0,
settlementAmount: 0,
transactionDate: new Date(),
fees: 0,
cardId: card.id,
cardReference: card.cardReference,
cardMaskedNumber: card.firstSixDigits + '******' + card.lastFourDigits,
accountId: card.account!.id,
transactionType: TransactionType.INTERNAL,
accountReference: card.account!.accountReference,
transactionScope: TransactionScope.CARD,
vatOnFees: 0,
}),
);
}
findTransactionByReference(transactionId: string, accountReference: string): Promise<Transaction | null> {
return this.transactionRepository.findOne({
where: { transactionId, accountReference },

View File

@ -27,15 +27,33 @@ export class AccountService {
return account;
}
async creditAccountBalance(accountReference: string, amount: number) {
async getAccountByIban(iban: string): Promise<Account> {
const account = await this.accountRepository.getAccountByIban(iban);
if (!account) {
throw new UnprocessableEntityException('ACCOUNT.NOT_FOUND');
}
return account;
}
creditAccountBalance(accountReference: string, amount: number) {
return this.accountRepository.topUpAccountBalance(accountReference, amount);
}
async getAccountByCustomerId(customerId: string): Promise<Account> {
const account = await this.accountRepository.getAccountByCustomerId(customerId);
if (!account) {
throw new UnprocessableEntityException('ACCOUNT.NOT_FOUND');
}
return account;
}
async decreaseAccountBalance(accountReference: string, amount: number) {
const account = await this.getAccountByReferenceNumber(accountReference);
/**
*
* While there is no need to check for insufficient balance because this is a webhook handler,
* I just added this check to ensure we don't have corruption in our data especially if this service is used elsewhere.
* I just added this check to ensure we don't have corruption in our data.
*/
if (account.balance < amount) {
@ -44,4 +62,21 @@ export class AccountService {
return this.accountRepository.decreaseAccountBalance(accountReference, amount);
}
increaseReservedBalance(account: Account, amount: number) {
if (account.balance < account.reservedBalance + amount) {
throw new UnprocessableEntityException('ACCOUNT.INSUFFICIENT_BALANCE');
}
return this.accountRepository.increaseReservedBalance(account.id, amount);
}
decrementReservedBalance(account: Account, amount: number) {
return this.accountRepository.decreaseReservedBalance(account.id, amount);
}
//THIS IS A MOCK FUNCTION FOR TESTING PURPOSES ONLY
async fundIban(iban: string, amount: number) {
const account = await this.getAccountByIban(iban);
return this.accountRepository.topUpAccountBalance(account.accountReference, amount);
}
}

View File

@ -1,19 +1,27 @@
import { BadRequestException, forwardRef, Inject, Injectable } from '@nestjs/common';
import { BadRequestException, forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
import Decimal from 'decimal.js';
import { Transactional } from 'typeorm-transactional';
import { AccountCardStatusChangedWebhookRequest } from '~/common/modules/neoleap/dtos/requests';
import { NeoLeapService } from '~/common/modules/neoleap/services';
import { Customer } from '~/customer/entities';
import { KycStatus } from '~/customer/enums';
import { CustomerService } from '~/customer/services';
import { OciService } from '~/document/services';
import { Card } from '../entities';
import { CardColors } from '../enums';
import { CardStatusMapper } from '../mappers/card-status.mapper';
import { CardRepository } from '../repositories';
import { AccountService } from './account.service';
import { TransactionService } from './transaction.service';
@Injectable()
export class CardService {
private readonly logger = new Logger(CardService.name);
constructor(
private readonly cardRepository: CardRepository,
private readonly accountService: AccountService,
private readonly ociService: OciService,
@Inject(forwardRef(() => TransactionService)) private readonly transactionService: TransactionService,
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
@Inject(forwardRef(() => CustomerService)) private readonly customerService: CustomerService,
) {}
@ -37,6 +45,24 @@ export class CardService {
return this.getCardById(createdCard.id);
}
async getChildCards(guardianId: string): Promise<Card[]> {
const cards = await this.cardRepository.findChildCardsForGuardian(guardianId);
await this.prepareJuniorImages(cards);
return cards;
}
async createCardForChild(parentCustomer: Customer, childCustomer: Customer, cardColor: CardColors, cardPin: string) {
const data = await this.neoleapService.createChildCard(parentCustomer, childCustomer, cardPin);
const createdCard = await this.cardRepository.createCard(
childCustomer.id,
parentCustomer.cards[0].account.id,
data,
cardColor,
parentCustomer.id,
);
return this.getCardById(createdCard.id);
}
async getCardById(id: string): Promise<Card> {
const card = await this.cardRepository.getCardById(id);
@ -71,6 +97,7 @@ export class CardService {
if (!card) {
throw new BadRequestException('CARD.NOT_FOUND');
}
return card;
}
@ -86,4 +113,61 @@ export class CardService {
return this.neoleapService.getEmbossingInformation(card);
}
async getChildCardEmbossingInformation(cardId: string, guardianId: string) {
const card = await this.getCardById(cardId);
if (card.parentId !== guardianId) {
throw new BadRequestException('CARD.DOES_NOT_BELONG_TO_GUARDIAN');
}
return this.neoleapService.getEmbossingInformation(card);
}
async updateCardLimit(cardId: string, newLimit: number) {
const { affected } = await this.cardRepository.updateCardLimit(cardId, newLimit);
if (affected === 0) {
throw new BadRequestException('CARD.NOT_FOUND');
}
}
async getIbanInformation(customerId: string) {
const account = await this.accountService.getAccountByCustomerId(customerId);
return account.iban;
}
@Transactional()
async transferToChild(juniorId: string, amount: number) {
const card = await this.getCardByCustomerId(juniorId);
if (amount > card.account.balance - card.account.reservedBalance) {
throw new BadRequestException('CARD.INSUFFICIENT_BALANCE');
}
const finalAmount = Decimal(amount).plus(card.limit);
await Promise.all([
this.neoleapService.updateCardControl(card.cardReference, finalAmount.toNumber()),
this.updateCardLimit(card.id, finalAmount.toNumber()),
this.accountService.increaseReservedBalance(card.account, amount),
this.transactionService.createInternalChildTransaction(card.id, amount),
]);
return finalAmount.toNumber();
}
fundIban(iban: string, amount: number) {
return this.accountService.fundIban(iban, amount);
}
private async prepareJuniorImages(cards: Card[]) {
this.logger.log(`Preparing junior images`);
await Promise.all(
cards.map(async (card) => {
const profilePicture = card.customer?.user?.profilePicture;
if (profilePicture) {
profilePicture.url = await this.ociService.generatePreSignedUrl(profilePicture);
}
}),
);
}
}

View File

@ -1,4 +1,4 @@
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
import { forwardRef, Inject, Injectable, UnprocessableEntityException } from '@nestjs/common';
import Decimal from 'decimal.js';
import { Transactional } from 'typeorm-transactional';
import {
@ -6,6 +6,7 @@ import {
CardTransactionWebhookRequest,
} from '~/common/modules/neoleap/dtos/requests';
import { Transaction } from '../entities/transaction.entity';
import { CustomerType } from '../enums';
import { TransactionRepository } from '../repositories/transaction.repository';
import { AccountService } from './account.service';
import { CardService } from './card.service';
@ -15,7 +16,7 @@ export class TransactionService {
constructor(
private readonly transactionRepository: TransactionRepository,
private readonly accountService: AccountService,
private readonly cardService: CardService,
@Inject(forwardRef(() => CardService)) private readonly cardService: CardService,
) {}
@Transactional()
@ -30,7 +31,14 @@ export class TransactionService {
const transaction = await this.transactionRepository.createCardTransaction(card, body);
const total = new Decimal(body.transactionAmount).plus(body.billingAmount).plus(body.fees).plus(body.vatOnFees);
if (card.customerType === CustomerType.CHILD) {
await Promise.all([
this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber()),
this.accountService.decrementReservedBalance(card.account, total.toNumber()),
]);
} else {
await this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber());
}
return transaction;
}
@ -51,6 +59,12 @@ export class TransactionService {
return transaction;
}
async createInternalChildTransaction(cardId: string, amount: number) {
const card = await this.cardService.getCardById(cardId);
const transaction = await this.transactionRepository.createInternalChildTransaction(card, amount);
return transaction;
}
private async findExistingTransaction(transactionId: string, accountReference: string): Promise<Transaction | null> {
const existingTransaction = await this.transactionRepository.findTransactionByReference(
transactionId,

View File

@ -1,11 +1,25 @@
export const CREATE_APPLICATION_MOCK = {
import { randomInt, randomUUID } from 'crypto';
/** Generate a string of `n` random digits (first digit never 0). */
function randomDigits(n: number): string {
if (n <= 0) return '0';
let s = String(randomInt(1, 10)); // first digit 19
for (let i = 1; i < n; i++) s += String(randomInt(0, 10));
return s;
}
/** Build a fresh mock object every time it's called */
export function buildCreateApplicationMock() {
const now = new Date().toISOString();
return {
ResponseHeader: {
Version: '1.0.0',
MsgUid: 'adaa1893-9f95-48a8-b7a1-0422bcf629b5',
MsgUid: randomUUID(),
Source: 'ZOD',
ServiceId: 'CreateNewApplication',
ReqDateTime: '2025-06-03T07:32:16.304Z',
RspDateTime: '2025-06-03T08:21:15.662',
ReqDateTime: now,
RspDateTime: now,
ResponseCode: '000',
ResponseType: 'Success',
ProcessingTime: 1665,
@ -73,26 +87,11 @@ export const CREATE_APPLICATION_MOCK = {
EmployerName: 'N/A',
EmploymentYears: 0,
EmploymentMonths: 0,
EmployerPhoneArea: null,
EmployerPhoneNumber: null,
EmployerPhoneExtension: null,
EmployerMobile: null,
EmployerFaxArea: null,
EmployerFax: null,
EmployerCity: null,
EmployerAddress: null,
EmploymentActivity: null,
EmploymentStatus: null,
CIF: null,
BankAccountNumber: ' ',
Currency: {
CurrCode: '682',
AlphaCode: 'SAR',
},
RequestedCurrencyList: null,
Currency: { CurrCode: '682', AlphaCode: 'SAR' },
CreditAccountNumber: '6000000000000000',
AccountType: '30',
OpenDate: null,
Income: 0,
AdditionalIncome: 0,
TotalIncome: 0,
@ -107,551 +106,28 @@ export const CREATE_APPLICATION_MOCK = {
AutoDebit: 'N',
PaymentMethod: '2',
BillingCycle: 'C1',
OldIssueDate: null,
OtherPaymentsDate: null,
MaximumDelinquency: null,
CreditBureauDecision: null,
CreditBureauUserData: null,
ECommerce: 'N',
NumberOfCards: 0,
OtherBank: null,
OtherBankDescription: null,
InsuranceProduct: null,
SocialCode: '000',
JobGrade: 0,
Flags: [
{
Position: 1,
Flags: Array.from({ length: 64 }, (_, i) => ({
Position: i + 1,
Value: '0',
},
{
Position: 2,
Value: '0',
},
{
Position: 3,
Value: '0',
},
{
Position: 4,
Value: '0',
},
{
Position: 5,
Value: '0',
},
{
Position: 6,
Value: '0',
},
{
Position: 7,
Value: '0',
},
{
Position: 8,
Value: '0',
},
{
Position: 9,
Value: '0',
},
{
Position: 10,
Value: '0',
},
{
Position: 11,
Value: '0',
},
{
Position: 12,
Value: '0',
},
{
Position: 13,
Value: '0',
},
{
Position: 14,
Value: '0',
},
{
Position: 15,
Value: '0',
},
{
Position: 16,
Value: '0',
},
{
Position: 17,
Value: '0',
},
{
Position: 18,
Value: '0',
},
{
Position: 19,
Value: '0',
},
{
Position: 20,
Value: '0',
},
{
Position: 21,
Value: '0',
},
{
Position: 22,
Value: '0',
},
{
Position: 23,
Value: '0',
},
{
Position: 24,
Value: '0',
},
{
Position: 25,
Value: '0',
},
{
Position: 26,
Value: '0',
},
{
Position: 27,
Value: '0',
},
{
Position: 28,
Value: '0',
},
{
Position: 29,
Value: '0',
},
{
Position: 30,
Value: '0',
},
{
Position: 31,
Value: '0',
},
{
Position: 32,
Value: '0',
},
{
Position: 33,
Value: '0',
},
{
Position: 34,
Value: '0',
},
{
Position: 35,
Value: '0',
},
{
Position: 36,
Value: '0',
},
{
Position: 37,
Value: '0',
},
{
Position: 38,
Value: '0',
},
{
Position: 39,
Value: '0',
},
{
Position: 40,
Value: '0',
},
{
Position: 41,
Value: '0',
},
{
Position: 42,
Value: '0',
},
{
Position: 43,
Value: '0',
},
{
Position: 44,
Value: '0',
},
{
Position: 45,
Value: '0',
},
{
Position: 46,
Value: '0',
},
{
Position: 47,
Value: '0',
},
{
Position: 48,
Value: '0',
},
{
Position: 49,
Value: '0',
},
{
Position: 50,
Value: '0',
},
{
Position: 51,
Value: '0',
},
{
Position: 52,
Value: '0',
},
{
Position: 53,
Value: '0',
},
{
Position: 54,
Value: '0',
},
{
Position: 55,
Value: '0',
},
{
Position: 56,
Value: '0',
},
{
Position: 57,
Value: '0',
},
{
Position: 58,
Value: '0',
},
{
Position: 59,
Value: '0',
},
{
Position: 60,
Value: '0',
},
{
Position: 61,
Value: '0',
},
{
Position: 62,
Value: '0',
},
{
Position: 63,
Value: '0',
},
{
Position: 64,
Value: '0',
},
],
CheckFlags: [
{
Position: 1,
})),
CheckFlags: Array.from({ length: 64 }, (_, i) => ({
Position: i + 1,
Value: '0',
})),
},
{
Position: 2,
Value: '0',
},
{
Position: 3,
Value: '0',
},
{
Position: 4,
Value: '0',
},
{
Position: 5,
Value: '0',
},
{
Position: 6,
Value: '0',
},
{
Position: 7,
Value: '0',
},
{
Position: 8,
Value: '0',
},
{
Position: 9,
Value: '0',
},
{
Position: 10,
Value: '0',
},
{
Position: 11,
Value: '0',
},
{
Position: 12,
Value: '0',
},
{
Position: 13,
Value: '0',
},
{
Position: 14,
Value: '0',
},
{
Position: 15,
Value: '0',
},
{
Position: 16,
Value: '0',
},
{
Position: 17,
Value: '0',
},
{
Position: 18,
Value: '0',
},
{
Position: 19,
Value: '0',
},
{
Position: 20,
Value: '0',
},
{
Position: 21,
Value: '0',
},
{
Position: 22,
Value: '0',
},
{
Position: 23,
Value: '0',
},
{
Position: 24,
Value: '0',
},
{
Position: 25,
Value: '0',
},
{
Position: 26,
Value: '0',
},
{
Position: 27,
Value: '0',
},
{
Position: 28,
Value: '0',
},
{
Position: 29,
Value: '0',
},
{
Position: 30,
Value: '0',
},
{
Position: 31,
Value: '0',
},
{
Position: 32,
Value: '0',
},
{
Position: 33,
Value: '0',
},
{
Position: 34,
Value: '0',
},
{
Position: 35,
Value: '0',
},
{
Position: 36,
Value: '0',
},
{
Position: 37,
Value: '0',
},
{
Position: 38,
Value: '0',
},
{
Position: 39,
Value: '0',
},
{
Position: 40,
Value: '0',
},
{
Position: 41,
Value: '0',
},
{
Position: 42,
Value: '0',
},
{
Position: 43,
Value: '0',
},
{
Position: 44,
Value: '0',
},
{
Position: 45,
Value: '0',
},
{
Position: 46,
Value: '0',
},
{
Position: 47,
Value: '0',
},
{
Position: 48,
Value: '0',
},
{
Position: 49,
Value: '0',
},
{
Position: 50,
Value: '0',
},
{
Position: 51,
Value: '0',
},
{
Position: 52,
Value: '0',
},
{
Position: 53,
Value: '0',
},
{
Position: 54,
Value: '0',
},
{
Position: 55,
Value: '0',
},
{
Position: 56,
Value: '0',
},
{
Position: 57,
Value: '0',
},
{
Position: 58,
Value: '0',
},
{
Position: 59,
Value: '0',
},
{
Position: 60,
Value: '0',
},
{
Position: 61,
Value: '0',
},
{
Position: 62,
Value: '0',
},
{
Position: 63,
Value: '0',
},
{
Position: 64,
Value: '0',
},
],
Maker: null,
Checker: null,
ReferredTo: null,
ReferralReason: null,
UserData1: null,
UserData2: null,
UserData3: null,
UserData4: null,
UserData5: null,
AdditionalFields: [],
},
ApplicationStatusDetails: {
StatusCode: '04',
Description: 'Approved',
Canceled: false,
},
CorporateDetails: null,
CustomerDetails: {
Id: 115158,
CustomerCode: '100000024619',
@ -660,8 +136,8 @@ export const CREATE_APPLICATION_MOCK = {
PreferredLanguage: 'EN',
ExternalCustomerCode: null,
Title: ' ',
FirstName: ' ',
LastName: ' ',
FirstName: ' ',
LastName: ' ',
DateOfBirth: null,
UserData1: '2031-09-17',
UserData2: '01',
@ -671,75 +147,46 @@ export const CREATE_APPLICATION_MOCK = {
Gender: 'U',
Married: 'U',
},
AccountDetailsList: [
{
Id: 21017,
Id: randomDigits(5),
InstitutionCode: '1100',
AccountNumber: '6899999999999999',
Currency: {
CurrCode: '682',
AlphaCode: 'SAR',
},
AccountNumber: randomDigits(16),
Currency: { CurrCode: '682', AlphaCode: 'SAR' },
AccountTypeCode: '30',
ClassId: '2',
AccountStatus: '00',
VipFlag: '0',
BlockedAmount: 0,
EquivalentBlockedAmount: null,
UnclearCredit: 0,
EquivalentUnclearCredit: null,
AvailableBalance: 0,
EquivalentAvailableBalance: null,
AvailableBalanceToSpend: 0,
CreditLimit: 0,
RemainingCashLimit: null,
UserData1: 'D36407C9AE4C28D2185',
UserData2: null,
UserData3: 'D36407C9AE4C28D2185',
UserData4: null,
UserData5: 'SA2380900000752991120011',
UserData5: `SA${randomDigits(22)}`,
},
],
CardDetailsList: [
{
pvv: null,
ResponseCardIdentifier: {
Id: 28595,
Id: randomDigits(5),
Pan: 'DDDDDDDDDDDDDDDDDDD',
MaskedPan: '999999_9999',
VPan: '1100000000000000',
VPan: randomDigits(16),
Seqno: 0,
},
ExpiryDate: '2031-09-30',
EffectiveDate: '2025-06-02',
CardStatus: '30',
OldPlasticExpiryDate: null,
OldPlasticCardStatus: null,
EmbossingName: 'ABDALHAMID AHMAD',
Title: 'Mr.',
FirstName: 'Abdalhamid',
LastName: ' Ahmad',
Additional: false,
BatchNumber: 8849,
ServiceCode: '226',
Kinship: null,
DateOfBirth: '1999-01-07',
LastActivity: null,
LastStatusChangeDate: '2025-06-03',
ActivationDate: null,
DateLastIssued: null,
PVV: null,
UserData: '4',
UserData1: '3',
UserData2: null,
UserData3: null,
UserData4: null,
UserData5: null,
Memo: null,
CardAuthorizationParameters: null,
L10NTitle: null,
L10NFirstName: null,
L10NLastName: null,
PinStatus: '40',
OldPinStatus: '0',
CustomerIdNumber: '1089055972',
@ -747,4 +194,5 @@ export const CREATE_APPLICATION_MOCK = {
},
],
},
};
};
}

View File

@ -10,8 +10,8 @@ import { InitiateKycRequestDto } from '~/customer/dtos/request';
import { Customer } from '~/customer/entities';
import { Gender } from '~/customer/enums';
import {
buildCreateApplicationMock,
CARD_EMBOSSING_DETAILS_MOCK,
CREATE_APPLICATION_MOCK,
INITIATE_KYC_MOCK,
INQUIRE_APPLICATION_MOCK,
} from '../__mocks__/';
@ -36,6 +36,7 @@ export class NeoLeapService {
private readonly zodApiUrl: string;
private readonly apiKey: string;
private readonly useGateway: boolean;
private readonly useKycMock: boolean;
private readonly institutionCode = '1100';
useLocalCert: boolean;
constructor(private readonly httpService: HttpService, private readonly configService: ConfigService) {
@ -44,12 +45,13 @@ export class NeoLeapService {
this.useGateway = [true, 'true'].includes(this.configService.get<boolean>('USE_GATEWAY', false));
this.useLocalCert = this.configService.get<boolean>('USE_LOCAL_CERT', false);
this.zodApiUrl = this.configService.getOrThrow<string>('ZOD_API_URL');
this.useKycMock = [true, 'true'].includes(this.configService.get<boolean>('USE_KYC_MOCK', true));
}
async initiateKyc(customerId: string, body: InitiateKycRequestDto) {
initiateKyc(customerId: string, body: InitiateKycRequestDto) {
const responseKey = 'InitiateKycResponseDetails';
if (!this.useGateway) {
if (this.useKycMock) {
const responseDto = plainToInstance(InitiateKycResponseDto, INITIATE_KYC_MOCK[responseKey], {
excludeExtraneousValues: true,
});
@ -89,11 +91,11 @@ export class NeoLeapService {
);
}
async createApplication(customer: Customer) {
createApplication(customer: Customer) {
const responseKey = 'CreateNewApplicationResponseDetails';
if (!this.useGateway) {
return plainToInstance(CreateApplicationResponse, CREATE_APPLICATION_MOCK[responseKey], {
return plainToInstance(CreateApplicationResponse, buildCreateApplicationMock()[responseKey], {
excludeExtraneousValues: true,
});
}
@ -163,7 +165,82 @@ export class NeoLeapService {
);
}
async inquireApplication(externalApplicationNumber: string) {
createChildCard(parent: Customer, child: Customer, cardPin: string) {
const responseKey = 'CreateNewApplicationResponseDetails';
if (!this.useGateway) {
return plainToInstance(CreateApplicationResponse, buildCreateApplicationMock()[responseKey], {
excludeExtraneousValues: true,
});
}
const payload: ICreateApplicationRequest = {
CreateNewApplicationRequestDetails: {
ApplicationRequestDetails: {
InstitutionCode: this.institutionCode,
ExternalApplicationNumber: child.applicationNumber.toString(),
ApplicationType: '01',
Product: '1101',
ApplicationDate: moment().format('YYYY-MM-DD'),
BranchCode: '000',
ApplicationSource: 'O',
DeliveryMethod: 'V',
},
ApplicationProcessingDetails: {
SuggestedLimit: 0,
RequestedLimit: 0,
AssignedLimit: 0,
ProcessControl: 'STND',
},
ApplicationFinancialInformation: {
Currency: {
AlphaCode: 'SAR',
},
BillingCycle: 'C1',
},
ApplicationOtherInfo: {
ParentAccountNumber: parent.cards[0].account.accountNumber,
},
ApplicationCustomerDetails: {
FirstName: parent.firstName,
LastName: parent.lastName,
FullName: parent.fullName,
DateOfBirth: moment(parent.dateOfBirth).format('YYYY-MM-DD'),
EmbossName: child.fullName.toUpperCase(), // TODO Enter Emboss Name
IdType: '01',
IdNumber: parent.nationalId,
IdExpiryDate: moment(parent.nationalIdExpiry).format('YYYY-MM-DD'),
Title: parent.gender === Gender.MALE ? 'Mr' : 'Ms',
Gender: parent.gender === Gender.MALE ? 'M' : 'F',
LocalizedDateOfBirth: moment(parent.dateOfBirth).format('YYYY-MM-DD'),
Nationality: CountriesNumericISO[parent.countryOfResidence],
},
ApplicationAddress: {
City: parent.city,
Country: CountriesNumericISO[parent.country],
Region: parent.region,
AddressLine1: `${parent.street} ${parent.building}`,
AddressLine2: parent.neighborhood,
AddressRole: 0,
Email: child.user.email,
Phone1: child.user.phoneNumber,
CountryDetails: {
DefaultCurrency: {},
Description: [],
},
},
},
RequestHeader: this.prepareHeaders('CreateNewApplication'),
};
return this.sendRequestToNeoLeap<ICreateApplicationRequest, CreateApplicationResponse>(
'application/CreateNewApplication',
payload,
responseKey,
CreateApplicationResponse,
);
}
inquireApplication(externalApplicationNumber: string) {
const responseKey = 'InquireApplicationResponseDetails';
if (!this.useGateway) {
return plainToInstance(InquireApplicationResponse, INQUIRE_APPLICATION_MOCK[responseKey], {
@ -195,7 +272,7 @@ export class NeoLeapService {
);
}
async updateCardControl(cardId: string, amount: number, count?: number) {
updateCardControl(cardId: string, amount: number, count?: number) {
const responseKey = 'UpdateCardControlResponseDetails';
if (!this.useGateway) {
return;
@ -224,7 +301,7 @@ export class NeoLeapService {
);
}
async getEmbossingInformation(card: Card) {
getEmbossingInformation(card: Card) {
const responseKey = 'GetEmbossingInformationResponseDetails';
if (!this.useGateway) {
return plainToInstance(CardEmbossingDetailsResponseDto, CARD_EMBOSSING_DETAILS_MOCK[responseKey], {
@ -244,7 +321,7 @@ export class NeoLeapService {
};
return this.sendRequestToNeoLeap<typeof payload, CardEmbossingDetailsResponseDto>(
'cardembossing/CardEmbossingDetails',
'issuance/GetEmbossingInformation',
payload,
responseKey,
CardEmbossingDetailsResponseDto,

View File

@ -21,7 +21,7 @@ export class NotificationCreatedListener {
/**
* Handles the NOTIFICATION_CREATED event by calling the appropriate channel logic.
*/
async handle(event: IEventInterface) {
handle(event: IEventInterface) {
this.logger.log(
`Handling ${EventType.NOTIFICATION_CREATED} event for notification ${event.id} (channel: ${event.channel})`,
);

View File

@ -68,7 +68,6 @@ export class NotificationsService {
});
this.logger.log(`emitting ${EventType.NOTIFICATION_CREATED} event`);
return this.redisPubSubService.publishEvent(EventType.NOTIFICATION_CREATED, {
...notification,
data: { otp },

View File

@ -19,7 +19,6 @@ export class OtpService {
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);

View File

@ -1,3 +1,4 @@
export * from './response.factory.util';
export * from './i18n-context-wrapper.util';
export * from './class-validator-formatter.util';
export * from './i18n-context-wrapper.util';
export * from './patch.util';
export * from './response.factory.util';

View File

@ -0,0 +1,3 @@
export const setIf = <T, K extends keyof T>(obj: T, key: K, val: T[K] | undefined) => {
if (typeof val !== 'undefined') obj[key] = val as T[K];
};

View File

@ -15,7 +15,7 @@ import { CountryIso } from '~/common/enums';
import { Guardian } from '~/guardian/entities/guradian.entity';
import { Junior } from '~/junior/entities';
import { User } from '~/user/entities';
import { CustomerStatus, KycStatus } from '../enums';
import { CustomerStatus, Gender, KycStatus } from '../enums';
@Entity('customers')
export class Customer extends BaseEntity {
@ -62,7 +62,7 @@ export class Customer extends BaseEntity {
isPep!: boolean;
@Column('varchar', { length: 255, nullable: true, name: 'gender' })
gender!: string;
gender!: Gender;
@Column('boolean', { default: false, name: 'is_junior' })
isJunior!: boolean;

View File

@ -14,8 +14,7 @@ export class CustomerRepository {
findOne(where: FindOptionsWhere<Customer>) {
return this.customerRepository.findOne({
where,
relations: ['user', 'cards'],
relations: ['user', 'cards', 'cards.account'],
});
}
@ -30,6 +29,7 @@ export class CustomerRepository {
lastName: body.lastName,
dateOfBirth: body.dateOfBirth,
countryOfResidence: body.countryOfResidence,
gender: body.gender,
}),
);
}

View File

@ -33,7 +33,10 @@ export class CustomerService {
async createJuniorCustomer(guardianId: string, juniorId: string, body: CreateJuniorRequestDto) {
this.logger.log(`Creating junior customer for user ${juniorId}`);
return this.customerRepository.createCustomer(juniorId, body, false);
await this.customerRepository.createCustomer(juniorId, body, false);
this.logger.log(`Junior customer created for user ${juniorId} successfully`);
return this.customerRepository.findOne({ id: juniorId });
}
async findCustomerById(id: string) {

View File

@ -0,0 +1,25 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateMoneyRequestsTable1757349525708 implements MigrationInterface {
name = 'CreateMoneyRequestsTable1757349525708';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "money_requests" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "amount" numeric(10,2) NOT NULL, "reason" character varying NOT NULL, "status" character varying NOT NULL DEFAULT 'PENDING', "rejection_reason" text, "junior_id" uuid NOT NULL, "guardian_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 "cards" ALTER COLUMN "color" SET DEFAULT 'DEEP_MAGENTA'`);
await queryRunner.query(
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_f7084c83efe7efaca37297d57ae" FOREIGN KEY ("junior_id") REFERENCES "juniors"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "money_requests" ADD CONSTRAINT "FK_09eadf4c4133b323f467ffc90f3" FOREIGN KEY ("guardian_id") REFERENCES "guardians"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_09eadf4c4133b323f467ffc90f3"`);
await queryRunner.query(`ALTER TABLE "money_requests" DROP CONSTRAINT "FK_f7084c83efe7efaca37297d57ae"`);
await queryRunner.query(`ALTER TABLE "cards" ALTER COLUMN "color" SET DEFAULT 'BLUE'`);
await queryRunner.query(`DROP TABLE "money_requests"`);
}
}

View File

@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddReservationAmountToAccountEntity1757433339849 implements MigrationInterface {
name = 'AddReservationAmountToAccountEntity1757433339849';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "accounts" ADD "reserved_balance" numeric(10,2) NOT NULL DEFAULT '0'`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "accounts" DROP COLUMN "reserved_balance"`);
}
}

View File

@ -1,3 +1,5 @@
export * from './1754913378460-initial-migration';
export * from './1754915164809-create-neoleap-related-entities';
export * from './1754915164810-seed-default-avatar';
export * from './1757349525708-create-money-requests-table';
export * from './1757433339849-add-reservation-amount-to-account-entity';

View File

@ -11,6 +11,7 @@ import {
} from 'typeorm';
import { Customer } from '~/customer/entities';
import { Junior } from '~/junior/entities';
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
@Entity('guardians')
export class Guardian extends BaseEntity {
@ -27,6 +28,9 @@ export class Guardian extends BaseEntity {
@OneToMany(() => Junior, (junior) => junior.guardian)
juniors!: Junior[];
@OneToMany(() => MoneyRequest, (moneyRequest) => moneyRequest.guardian)
moneyRequests!: MoneyRequest[];
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
createdAt!: Date;

View File

@ -51,7 +51,8 @@
"NOT_FOUND": "لم يتم العثور على العميل.",
"ALREADY_EXISTS": "العميل موجود بالفعل.",
"KYC_NOT_APPROVED": "لم يتم الموافقة على هوية العميل بعد.",
"ALREADY_HAS_CARD": "العميل لديه بطاقة بالفعل."
"ALREADY_HAS_CARD": "العميل لديه بطاقة بالفعل.",
"DOES_NOT_HAVE_CARD": "العميل لا يملك بطاقة."
},
"GIFT": {
@ -66,16 +67,14 @@
"NOT_FOUND": "لم يتم العثور على الطفل.",
"CIVIL_ID_REQUIRED": "مطلوب بطاقة الهوية المدنية.",
"CIVIL_ID_NOT_CREATED_BY_GUARDIAN": "تم تحميل بطاقة الهوية المدنية من قبل شخص آخر غير ولي الأمر.",
"CIVIL_ID_ALREADY_EXISTS": "بطاقة الهوية المدنية مستخدمة بالفعل من قبل طفل آخر."
"CIVIL_ID_ALREADY_EXISTS": "بطاقة الهوية المدنية مستخدمة بالفعل من قبل طفل آخر.",
"CANNOT_UPDATE_REGISTERED_USER": "الطفل قد سجل بالفعل. لا يُسمح بتحديث البيانات."
},
"MONEY_REQUEST": {
"START_DATE_IN_THE_PAST": "لا يمكن أن يكون تاريخ البدء في الماضي.",
"END_DATE_IN_THE_PAST": "لا يمكن أن يكون تاريخ النهاية في الماضي.",
"END_DATE_BEFORE_START_DATE": "لا يمكن أن يكون تاريخ النهاية قبل تاريخ البدء.",
"NOT_FOUND": "لم يتم العثور على طلب المال.",
"ENDED": "تم انتهاء طلب المال.",
"ALREADY_REVIEWED": "تمت مراجعة طلب المال بالفعل."
"ALREADY_APPROVED": "تمت الموافقة على طلب المال بالفعل.",
"ALREADY_REJECTED": "تم رفض طلب المال بالفعل."
},
"GOAL": {
@ -101,5 +100,9 @@
},
"OTP": {
"INVALID_OTP": "رمز التحقق الذي أدخلته غير صالح. يرجى المحاولة مرة أخرى."
},
"CARD": {
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر."
}
}

View File

@ -50,7 +50,8 @@
"NOT_FOUND": "The customer was not found.",
"ALREADY_EXISTS": "The customer already exists.",
"KYC_NOT_APPROVED": "The customer's KYC has not been approved yet.",
"ALREADY_HAS_CARD": "The customer already has a card."
"ALREADY_HAS_CARD": "The customer already has a card.",
"DOES_NOT_HAVE_CARD": "The customer does not have a card."
},
"GIFT": {
@ -65,16 +66,14 @@
"NOT_FOUND": "The junior was not found.",
"CIVIL_ID_REQUIRED": "Civil ID is required.",
"CIVIL_ID_NOT_CREATED_BY_GUARDIAN": "The civil ID document was not uploaded by the guardian.",
"CIVIL_ID_ALREADY_EXISTS": "The civil ID is already used by another junior."
"CIVIL_ID_ALREADY_EXISTS": "The civil ID is already used by another junior.",
"CANNOT_UPDATE_REGISTERED_USER": "The junior has already registered. Updating details is not allowed."
},
"MONEY_REQUEST": {
"START_DATE_IN_THE_PAST": "The start date cannot be in the past.",
"END_DATE_IN_THE_PAST": "The end date cannot be in the past.",
"END_DATE_BEFORE_START_DATE": "The end date cannot be before the start date.",
"NOT_FOUND": "The money request was not found.",
"ENDED": "The money request has ended.",
"ALREADY_REVIEWED": "The money request has already been reviewed."
"ALREADY_APPROVED": "The money request has already been approved.",
"ALREADY_REJECTED": "The money request has already been rejected."
},
"GOAL": {
@ -100,5 +99,9 @@
},
"OTP": {
"INVALID_OTP": "The OTP you entered is invalid. Please try again."
},
"CARD": {
"INSUFFICIENT_BALANCE": "The card does not have sufficient balance to complete this transfer.",
"DOES_NOT_BELONG_TO_GUARDIAN": "The card does not belong to the guardian."
}
}

View File

@ -1,4 +1,4 @@
import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Roles } from '~/auth/enums';
import { IJwtPayload } from '~/auth/interfaces';
@ -8,8 +8,18 @@ import { ApiDataPageResponse, ApiDataResponse, ApiLangRequestHeader } from '~/co
import { PageOptionsRequestDto } from '~/core/dtos';
import { CustomParseUUIDPipe } from '~/core/pipes';
import { ResponseFactory } from '~/core/utils';
import { CreateJuniorRequestDto, SetThemeRequestDto } from '../dtos/request';
import { JuniorResponseDto, QrCodeValidationResponseDto, ThemeResponseDto } from '../dtos/response';
import {
CreateJuniorRequestDto,
SetThemeRequestDto,
TransferToJuniorRequestDto,
UpdateJuniorRequestDto,
} from '../dtos/request';
import {
JuniorResponseDto,
QrCodeValidationResponseDto,
ThemeResponseDto,
TransferToJuniorResponseDto,
} from '../dtos/response';
import { JuniorService } from '../services';
@Controller('juniors')
@ -59,6 +69,20 @@ export class JuniorController {
return ResponseFactory.data(new JuniorResponseDto(junior));
}
@Patch(':juniorId')
@UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(JuniorResponseDto)
async updateJunior(
@AuthenticatedUser() user: IJwtPayload,
@Param('juniorId', CustomParseUUIDPipe) juniorId: string,
@Body() body: UpdateJuniorRequestDto,
) {
const junior = await this.juniorService.updateJunior(juniorId, body, user.sub);
return ResponseFactory.data(new JuniorResponseDto(junior));
}
@Post('set-theme')
@UseGuards(RolesGuard)
@AllowedRoles(Roles.JUNIOR)
@ -86,4 +110,18 @@ export class JuniorController {
return ResponseFactory.data(new QrCodeValidationResponseDto(junior));
}
@Post(':juniorId/transfer')
@UseGuards(RolesGuard)
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(TransferToJuniorResponseDto)
async transferToJunior(
@AuthenticatedUser() user: IJwtPayload,
@Param('juniorId', CustomParseUUIDPipe) juniorId: string,
@Body() body: TransferToJuniorRequestDto,
) {
const newAmount = await this.juniorService.transferToJunior(juniorId, body, user.sub);
return ResponseFactory.data(new TransferToJuniorResponseDto(newAmount));
}
}

View File

@ -1,25 +1,19 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsDateString, IsEmail, IsEnum, IsNotEmpty, IsOptional, IsString, IsUUID, Matches } from 'class-validator';
import {
IsDateString,
IsEmail,
IsEnum,
IsNotEmpty,
IsNumberString,
IsOptional,
IsString,
IsUUID,
} from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { COUNTRY_CODE_REGEX } from '~/auth/constants';
import { IsValidPhoneNumber } from '~/core/decorators/validations';
import { CardColors } from '~/card/enums';
import { Gender } from '~/customer/enums';
import { Relationship } from '~/junior/enums';
export class CreateJuniorRequestDto {
@ApiProperty({ example: '+962' })
@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' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'customer.firstName' }) })
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.firstName' }) })
@ -30,9 +24,9 @@ export class CreateJuniorRequestDto {
@IsNotEmpty({ message: i18n('validation.IsNotEmpty', { path: 'general', property: 'customer.lastName' }) })
lastName!: string;
@ApiProperty({ example: 'MALE' })
@ApiProperty({ enum: Gender })
@IsEnum(Gender, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.gender' }) })
gender!: string;
gender!: Gender;
@ApiProperty({ example: '2020-01-01' })
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.dateOfBirth' }) })
@ -46,13 +40,13 @@ export class CreateJuniorRequestDto {
@IsEnum(Relationship, { message: i18n('validation.IsEnum', { path: 'general', property: 'junior.relationship' }) })
relationship!: Relationship;
@ApiProperty({ example: 'bf342-3f3f-3f3f-3f3f' })
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'junior.civilIdFrontId' }) })
civilIdFrontId!: string;
@ApiProperty({ enum: CardColors })
@IsEnum(CardColors, { message: i18n('validation.IsEnum', { path: 'general', property: 'junior.cardColor' }) })
cardColor!: CardColors;
@ApiProperty({ example: 'bf342-3f3f-3f3f-3f3f' })
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'junior.civilIdBackId' }) })
civilIdBackId!: string;
@ApiProperty({ example: '1234' })
@IsNumberString({}, { message: i18n('validation.IsEnum', { path: 'general', property: 'junior.cardPin' }) })
cardPin!: string;
@ApiProperty({ example: '123e4567-e89b-12d3-a456-426614174000' })
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'customer.profilePictureId' }) })

View File

@ -1,2 +1,4 @@
export * from './create-junior.request.dto';
export * from './set-theme.request.dto';
export * from './transfer-to-junior.request.dto';
export * from './update-junior.request.dto';

View File

@ -0,0 +1,12 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNumber } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
export class TransferToJuniorRequestDto {
@ApiProperty({ example: 300.42 })
@IsNumber(
{ maxDecimalPlaces: 3 },
{ message: i18n('validation.IsNumber', { path: 'general', property: 'transferToJunior.amount' }) },
)
amount!: number;
}

View File

@ -0,0 +1,5 @@
import { OmitType, PartialType } from '@nestjs/swagger';
import { CreateJuniorRequestDto } from './create-junior.request.dto';
const omitted = OmitType(CreateJuniorRequestDto, ['cardColor', 'cardPin']);
export class UpdateJuniorRequestDto extends PartialType(omitted) {}

View File

@ -2,3 +2,4 @@ export * from './junior.response.dto';
export * from './qr-code-validation-details.response.dto';
export * from './qr-code-validation.response.dto';
export * from './theme.response.dto';
export * from './transfer-to-junior.response.dto';

View File

@ -1,25 +1,51 @@
import { ApiProperty } from '@nestjs/swagger';
import { Gender } from '~/customer/enums';
import { DocumentMetaResponseDto } from '~/document/dtos/response';
import { Junior } from '~/junior/entities';
import { Relationship } from '~/junior/enums';
import { GuardianRelationship, Relationship } from '~/junior/enums';
export class JuniorResponseDto {
@ApiProperty({ example: 'id' })
id!: string;
@ApiProperty({ example: 'fullName' })
fullName!: string;
@ApiProperty({ example: 'FirstName' })
firstName!: string;
@ApiProperty({ example: 'relationship' })
@ApiProperty({ example: 'LastName' })
lastName!: string;
@ApiProperty({ example: 'test@junior.com' })
email!: string;
@ApiProperty({ example: Gender.MALE })
gender!: Gender;
@ApiProperty({ example: '2000-01-01' })
dateOfBirth!: Date;
@ApiProperty({ enum: Relationship })
relationship!: Relationship;
@ApiProperty({ enum: GuardianRelationship })
guardianRelationship!: GuardianRelationship;
@ApiProperty({ type: DocumentMetaResponseDto })
profilePicture!: DocumentMetaResponseDto | null;
@ApiProperty({ example: 2000.0, description: 'The available balance' })
availableBalance!: number | null;
constructor(junior: Junior) {
const card = junior.customer?.cards?.[0];
this.id = junior.id;
this.fullName = `${junior.customer.firstName} ${junior.customer.lastName}`;
this.firstName = junior.customer.firstName;
this.lastName = junior.customer.lastName;
this.email = junior.customer.user.email;
this.gender = junior.customer.gender;
this.dateOfBirth = junior.customer.dateOfBirth;
this.relationship = junior.relationship;
this.guardianRelationship = GuardianRelationship[junior.relationship];
this.availableBalance = card ? Math.min(card.limit, card.account.balance) : null;
this.profilePicture = junior.customer.user.profilePicture
? new DocumentMetaResponseDto(junior.customer.user.profilePicture)
: null;

View File

@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
export class TransferToJuniorResponseDto {
@ApiProperty({ example: 300.42 })
newAmount!: number;
constructor(newAmount: number) {
this.newAmount = newAmount;
}
}

View File

@ -5,12 +5,14 @@ import {
Entity,
JoinColumn,
ManyToOne,
OneToMany,
OneToOne,
PrimaryColumn,
UpdateDateColumn,
} from 'typeorm';
import { Customer } from '~/customer/entities';
import { Guardian } from '~/guardian/entities/guradian.entity';
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
import { Relationship } from '../enums';
import { Theme } from './theme.entity';
@ -39,6 +41,9 @@ export class Junior extends BaseEntity {
@JoinColumn({ name: 'guardian_id' })
guardian!: Guardian;
@OneToMany(() => MoneyRequest, (moneyRequest) => moneyRequest.junior)
moneyRequests!: MoneyRequest[];
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
createdAt!: Date;

View File

@ -1,6 +1,8 @@
import { HttpModule } from '@nestjs/axios';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CardModule } from '~/card/card.module';
import { NeoLeapModule } from '~/common/modules/neoleap/neoleap.module';
import { CustomerModule } from '~/customer/customer.module';
import { UserModule } from '~/user/user.module';
import { JuniorController } from './controllers';
@ -11,7 +13,14 @@ import { BranchIoService, JuniorService, QrcodeService } from './services';
@Module({
controllers: [JuniorController],
providers: [JuniorService, JuniorRepository, QrcodeService, BranchIoService],
imports: [TypeOrmModule.forFeature([Junior, Theme]), UserModule, CustomerModule, HttpModule],
imports: [
TypeOrmModule.forFeature([Junior, Theme]),
UserModule,
CustomerModule,
HttpModule,
NeoLeapModule,
CardModule,
],
exports: [JuniorService],
})
export class JuniorModule {}

View File

@ -13,14 +13,28 @@ export class JuniorRepository {
findJuniorsByGuardianId(guardianId: string, pageOptions: PageOptionsRequestDto) {
return this.juniorRepository.findAndCount({
where: { guardianId },
relations: ['customer', 'customer.user', 'customer.user.profilePicture'],
relations: [
'customer',
'customer.user',
'customer.user.profilePicture',
'customer.cards',
'customer.cards.account',
],
skip: (pageOptions.page - FIRST_PAGE) * pageOptions.size,
take: pageOptions.size,
});
}
findJuniorById(juniorId: string, withGuardianRelation = false, guardianId?: string) {
const relations = ['customer', 'customer.user', 'theme', 'theme.avatar'];
const relations = [
'customer',
'customer.user',
'theme',
'theme.avatar',
'customer.user.profilePicture',
'customer.cards',
'customer.cards.account',
];
if (withGuardianRelation) {
relations.push('guardian', 'guardian.customer', 'guardian.customer.user');
}

View File

@ -1,15 +1,21 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { FindOptionsWhere } from 'typeorm';
import { Transactional } from 'typeorm-transactional';
import { Roles } from '~/auth/enums';
import { CardService } from '~/card/services';
import { NeoLeapService } from '~/common/modules/neoleap/services';
import { PageOptionsRequestDto } from '~/core/dtos';
import { setIf } from '~/core/utils';
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';
import { CreateJuniorRequestDto, SetThemeRequestDto } from '../dtos/request';
import {
CreateJuniorRequestDto,
SetThemeRequestDto,
TransferToJuniorRequestDto,
UpdateJuniorRequestDto,
} from '../dtos/request';
import { Junior } from '../entities';
import { JuniorRepository } from '../repositories';
import { QrcodeService } from './qrcode.service';
@ -25,43 +31,47 @@ export class JuniorService {
private readonly documentService: DocumentService,
private readonly ociService: OciService,
private readonly qrCodeService: QrcodeService,
private readonly neoleapService: NeoLeapService,
private readonly cardService: CardService,
) {}
@Transactional()
async createJuniors(body: CreateJuniorRequestDto, guardianId: string) {
this.logger.log(`Creating junior for guardian ${guardianId}`);
const searchConditions: FindOptionsWhere<User>[] = [{ email: body.email }];
const parentCustomer = await this.customerService.findCustomerById(guardianId);
if (body.phoneNumber && body.countryCode) {
searchConditions.push({
phoneNumber: body.phoneNumber,
countryCode: body.countryCode,
});
if (!parentCustomer.cards || parentCustomer.cards.length === 0) {
this.logger.error(`Guardian ${guardianId} does not have a card`);
throw new BadRequestException('CUSTOMER.DOES_NOT_HAVE_CARD');
}
const existingUser = await this.userService.findUser(searchConditions);
const existingUser = await this.userService.findUser({ email: body.email });
if (existingUser) {
this.logger.error(`User with email ${body.email} or phone number ${body.phoneNumber} already exists`);
this.logger.error(`User with email ${body.email} already exists`);
throw new BadRequestException('USER.ALREADY_EXISTS');
}
const user = await this.userService.createUser({
email: body.email,
countryCode: body.countryCode,
phoneNumber: body.phoneNumber,
firstName: body.firstName,
lastName: body.lastName,
profilePictureId: body.profilePictureId,
roles: [Roles.JUNIOR],
});
const customer = await this.customerService.createJuniorCustomer(guardianId, user.id, body);
const childCustomer = await this.customerService.createJuniorCustomer(guardianId, user.id, body);
await this.juniorRepository.createJunior(user.id, {
guardianId,
relationship: body.relationship,
customerId: customer.id,
customerId: childCustomer!.id,
});
this.logger.debug('Creating card For Child');
await this.cardService.createCardForChild(parentCustomer, childCustomer!, body.cardColor, body.cardColor);
this.logger.log(`Junior ${user.id} created successfully`);
return this.generateToken(user.id);
@ -75,11 +85,45 @@ export class JuniorService {
this.logger.error(`Junior ${juniorId} not found`);
throw new BadRequestException('JUNIOR.NOT_FOUND');
}
await this.prepareJuniorImages([junior]);
this.logger.log(`Junior ${juniorId} found successfully`);
return junior;
}
async updateJunior(juniorId: string, body: UpdateJuniorRequestDto, guardianId: string) {
this.logger.log(`Updating junior ${juniorId}`);
const junior = await this.findJuniorById(juniorId, false, guardianId);
const customer = junior.customer;
const user = customer.user;
if (user.password) {
this.logger.error(`Cannot update junior ${juniorId} with registered user`);
throw new BadRequestException('JUNIOR.CANNOT_UPDATE_REGISTERED_USER');
}
if (body.email) {
const existingUser = await this.userService.findUser({ email: body.email });
if (existingUser && existingUser.id !== junior.customer.user.id) {
this.logger.error(`User with email ${body.email} already exists`);
throw new BadRequestException('USER.ALREADY_EXISTS');
}
junior.customer.user.email = body.email;
}
setIf(user, 'profilePictureId', body.profilePictureId);
setIf(user, 'firstName', body.firstName);
setIf(user, 'lastName', body.lastName);
setIf(customer, 'firstName', body.firstName);
setIf(customer, 'lastName', body.lastName);
setIf(customer, 'dateOfBirth', body.dateOfBirth as unknown as Date);
setIf(junior, 'relationship', body.relationship);
await Promise.all([junior.save(), customer.save(), user.save()]);
this.logger.log(`Junior ${juniorId} updated successfully`);
return junior;
}
@Transactional()
async setTheme(body: SetThemeRequestDto, juniorId: string) {
this.logger.log(`Setting theme for junior ${juniorId}`);
@ -128,6 +172,17 @@ export class JuniorService {
return !!junior;
}
async transferToJunior(juniorId: string, body: TransferToJuniorRequestDto, guardianId: string) {
const doesBelong = await this.doesJuniorBelongToGuardian(guardianId, juniorId);
if (!doesBelong) {
this.logger.error(`Junior ${juniorId} does not belong to guardian ${guardianId}`);
throw new BadRequestException('JUNIOR.NOT_BELONG_TO_GUARDIAN');
}
return this.cardService.transferToChild(juniorId, body.amount);
}
private async prepareJuniorImages(juniors: Junior[]) {
this.logger.log(`Preparing junior images`);
await Promise.all(

View File

@ -10,7 +10,6 @@ export class QrcodeService {
this.logger.log(`Generating QR code for token ${token}`);
const link = await this.branchIoService.createBranchLink(token);
return qrcode.toDataURL(link);
}
}

View File

@ -0,0 +1 @@
export * from './money-requests.controller';

View File

@ -0,0 +1,81 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { Roles } from '~/auth/enums';
import { IJwtPayload } from '~/auth/interfaces';
import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
import { AccessTokenGuard, RolesGuard } from '~/common/guards';
import { ApiDataResponse } from '~/core/decorators';
import { ResponseFactory } from '~/core/utils';
import { CreateMoneyRequestDto, MoneyRequestsFiltersRequestDto, RejectionMoneyRequestDto } from '../dtos/request';
import { MoneyRequestResponseDto } from '../dtos/response/money-request.response.dto';
import { MoneyRequestsService } from '../services/money-requests.service';
@Controller('money-requests')
@ApiTags('Money Requests')
@UseGuards(AccessTokenGuard, RolesGuard)
@ApiBearerAuth()
export class MoneyRequestsController {
constructor(private readonly moneyRequestsService: MoneyRequestsService) {}
@Post()
@AllowedRoles(Roles.JUNIOR)
@ApiDataResponse(MoneyRequestResponseDto)
async createMoneyRequest(@AuthenticatedUser() { sub }: IJwtPayload, @Body() body: CreateMoneyRequestDto) {
const moneyRequest = await this.moneyRequestsService.createMoneyRequest(sub, body);
return ResponseFactory.data(new MoneyRequestResponseDto(moneyRequest));
}
@Get()
@AllowedRoles(Roles.JUNIOR, Roles.GUARDIAN)
@ApiDataResponse(MoneyRequestResponseDto)
async getMoneyRequests(
@AuthenticatedUser() { sub, roles }: IJwtPayload,
@Query() filters: MoneyRequestsFiltersRequestDto,
) {
const [moneyRequests, count] = await this.moneyRequestsService.findMoneyRequests(
sub,
roles.includes(Roles.GUARDIAN) ? Roles.GUARDIAN : Roles.JUNIOR,
filters,
);
return ResponseFactory.dataPage(
moneyRequests.map((mr) => new MoneyRequestResponseDto(mr)),
{
page: filters.page,
size: filters.size,
itemCount: count,
},
);
}
@Get(':id')
@AllowedRoles(Roles.JUNIOR, Roles.GUARDIAN)
@ApiDataResponse(MoneyRequestResponseDto)
async getMoneyRequest(@Param('id') id: string, @AuthenticatedUser() { sub, roles }: IJwtPayload) {
const moneyRequest = await this.moneyRequestsService.findById(
id,
sub,
roles.includes(Roles.GUARDIAN) ? Roles.GUARDIAN : Roles.JUNIOR,
);
return ResponseFactory.data(new MoneyRequestResponseDto(moneyRequest));
}
@Patch(':id/approve')
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(MoneyRequestResponseDto)
@HttpCode(HttpStatus.NO_CONTENT)
async approveMoneyRequest(@Param('id') id: string, @AuthenticatedUser() { sub }: IJwtPayload) {
await this.moneyRequestsService.approveMoneyRequest(id, sub);
}
@Patch(':id/reject')
@AllowedRoles(Roles.GUARDIAN)
@ApiDataResponse(MoneyRequestResponseDto)
@HttpCode(HttpStatus.NO_CONTENT)
async rejectMoneyRequest(
@Param('id') id: string,
@AuthenticatedUser() { sub }: IJwtPayload,
@Body() rejectionReasondto: RejectionMoneyRequestDto,
) {
await this.moneyRequestsService.rejectMoneyRequest(id, sub, rejectionReasondto);
}
}

View File

@ -0,0 +1,15 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNumber, IsString } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
export class CreateMoneyRequestDto {
@ApiProperty({ example: 300.42 })
@IsNumber(
{ maxDecimalPlaces: 3 },
{ message: i18n('validation.IsNumber', { path: 'general', property: 'moneyRequest.amount' }) },
)
amount!: number;
@ApiProperty({ example: 'For school supplies' })
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'moneyRequest.reason' }) })
reason!: string;
}

View File

@ -0,0 +1,3 @@
export * from './create-money-request.request.dto';
export * from './money-requests-filters.request.dto';
export * from './rejection.request.dto';

View File

@ -0,0 +1,13 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
import { PageOptionsRequestDto } from '~/core/dtos';
import { MoneyRequestStatus } from '~/money-request/enums';
export class MoneyRequestsFiltersRequestDto extends PageOptionsRequestDto {
@ApiPropertyOptional({ example: MoneyRequestStatus.APPROVED, enum: MoneyRequestStatus })
@IsEnum(MoneyRequestStatus, {
message: i18n('validation.enum', { property: 'moneyRequest.status', enum: MoneyRequestStatus }),
})
@IsOptional()
status?: MoneyRequestStatus;
}

View File

@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
export class RejectionMoneyRequestDto {
@ApiProperty({ example: 'You are spending too much' })
@IsString({ message: i18n('validation.string', { property: 'rejectionReason' }) })
@IsOptional()
rejectionReason!: string;
}

View File

@ -0,0 +1,41 @@
import { ApiProperty } from '@nestjs/swagger';
import { JuniorResponseDto } from '~/junior/dtos/response';
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
import { MoneyRequestStatus } from '~/money-request/enums';
export class MoneyRequestResponseDto {
@ApiProperty({ example: '123e4567-e89b-12d3-a456-426614174000' })
id!: string;
@ApiProperty({ example: 300.42 })
amount!: number;
@ApiProperty({ example: 'For school supplies' })
reason!: string;
@ApiProperty({ enum: MoneyRequestStatus, example: MoneyRequestStatus.PENDING })
status!: MoneyRequestStatus;
@ApiProperty({ example: null })
rejectionReason!: string | null;
@ApiProperty({ type: JuniorResponseDto })
junior!: JuniorResponseDto;
@ApiProperty({ example: '2024-01-01T00:00:00.000Z' })
createdAt!: Date;
@ApiProperty({ example: '2024-01-02T00:00:00.000Z' })
updatedAt!: Date;
constructor(data: MoneyRequest) {
this.id = data.id;
this.amount = Number(data.amount);
this.reason = data.reason;
this.status = data.status;
this.rejectionReason = data.rejectionReason;
this.junior = new JuniorResponseDto(data.junior);
this.createdAt = data.createdAt;
this.updatedAt = data.updatedAt;
}
}

View File

@ -0,0 +1,51 @@
import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { Guardian } from '~/guardian/entities/guradian.entity';
import { Junior } from '~/junior/entities';
import { MoneyRequestStatus } from '../enums';
@Entity('money_requests')
export class MoneyRequest extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id!: string;
@Column({ precision: 10, scale: 2, type: 'decimal', name: 'amount' })
amount!: number;
@Column({ type: 'varchar', name: 'reason' })
reason!: string;
@Column({ type: 'varchar', name: 'status', default: MoneyRequestStatus.PENDING })
status!: MoneyRequestStatus;
@Column({ type: 'text', name: 'rejection_reason', nullable: true })
rejectionReason!: string | null;
@Column({ type: 'uuid', name: 'junior_id' })
juniorId!: string;
@Column({ type: 'uuid', name: 'guardian_id' })
guardianId!: string;
@ManyToOne(() => Junior, (junior) => junior.moneyRequests, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'junior_id' })
junior!: Junior;
@ManyToOne(() => Guardian, (guardian) => guardian.moneyRequests, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'guardian_id' })
guardian!: Guardian;
@CreateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'created_at' })
createdAt!: Date;
@UpdateDateColumn({ type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP', name: 'updated_at' })
updatedAt!: Date;
}

View File

@ -0,0 +1 @@
export * from './money-request-status.enum';

View File

@ -0,0 +1,5 @@
export enum MoneyRequestStatus {
PENDING = 'PENDING',
APPROVED = 'APPROVED',
REJECTED = 'REJECTED',
}

View File

@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JuniorModule } from '~/junior/junior.module';
import { MoneyRequestsController } from './controllers';
import { MoneyRequest } from './entities/money-request.entity';
import { MoneyRequestsRepository } from './repositories';
import { MoneyRequestsService } from './services';
@Module({
imports: [TypeOrmModule.forFeature([MoneyRequest]), JuniorModule],
controllers: [MoneyRequestsController],
providers: [MoneyRequestsService, MoneyRequestsRepository],
})
export class MoneyRequestModule {}

View File

@ -0,0 +1 @@
export * from './money-requests.repository';

View File

@ -0,0 +1,70 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Roles } from '~/auth/enums/roles.enum';
import { CreateMoneyRequestDto, MoneyRequestsFiltersRequestDto } from '../dtos/request';
import { MoneyRequest } from '../entities/money-request.entity';
import { MoneyRequestStatus } from '../enums';
const FIRST_PAGE = 1;
@Injectable()
export class MoneyRequestsRepository {
constructor(@InjectRepository(MoneyRequest) private readonly moneyRequestRepository: Repository<MoneyRequest>) {}
findAll(userId: string, role: Roles, filters: MoneyRequestsFiltersRequestDto): Promise<[MoneyRequest[], number]> {
const queryBuilder = this.moneyRequestRepository.createQueryBuilder('moneyRequest');
if (role === Roles.JUNIOR) {
queryBuilder.where('moneyRequest.juniorId = :userId', { userId });
} else if (role === Roles.GUARDIAN) {
queryBuilder.where('moneyRequest.guardianId = :userId', { userId });
}
queryBuilder.leftJoinAndSelect('moneyRequest.junior', 'junior');
queryBuilder.leftJoinAndSelect('junior.customer', 'customer');
queryBuilder.leftJoinAndSelect('customer.user', 'user');
queryBuilder.leftJoinAndSelect('user.profilePicture', 'profilePicture');
if (filters.status) {
queryBuilder.andWhere('moneyRequest.status = :status', { status: filters.status });
}
queryBuilder.skip((filters.page - FIRST_PAGE) * filters.size);
queryBuilder.take(filters.size);
queryBuilder.orderBy('moneyRequest.createdAt', 'DESC');
return queryBuilder.getManyAndCount();
}
createMoneyRequest(juniorId: string, guardianId: string, body: CreateMoneyRequestDto): Promise<MoneyRequest> {
return this.moneyRequestRepository.save(
this.moneyRequestRepository.create({
amount: body.amount,
reason: body.reason,
status: MoneyRequestStatus.PENDING,
juniorId,
guardianId,
}),
);
}
findById(id: string, userId?: string, role?: Roles): Promise<MoneyRequest | null> {
const whereCondition: any = { id };
if (role === Roles.JUNIOR) {
whereCondition.juniorId = userId;
} else {
whereCondition.guardianId = userId;
}
return this.moneyRequestRepository.findOne({
where: whereCondition,
relations: ['junior', 'junior.customer', 'junior.customer.user', 'junior.customer.user.profilePicture'],
});
}
approveMoneyRequest(id: string) {
return this.moneyRequestRepository.update({ id }, { status: MoneyRequestStatus.APPROVED });
}
rejectMoneyRequest(id: string, rejectionReason?: string) {
return this.moneyRequestRepository.update({ id }, { status: MoneyRequestStatus.REJECTED, rejectionReason });
}
}

View File

@ -0,0 +1 @@
export * from './money-requests.service';

View File

@ -0,0 +1,102 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { Transactional } from 'typeorm-transactional';
import { Roles } from '~/auth/enums';
import { OciService } from '~/document/services';
import { Junior } from '~/junior/entities/junior.entity';
import { JuniorService } from '~/junior/services';
import { CreateMoneyRequestDto, MoneyRequestsFiltersRequestDto, RejectionMoneyRequestDto } from '../dtos/request';
import { MoneyRequest } from '../entities/money-request.entity';
import { MoneyRequestStatus } from '../enums';
import { MoneyRequestsRepository } from '../repositories';
@Injectable()
export class MoneyRequestsService {
private readonly logger = new Logger(MoneyRequestsService.name);
constructor(
private readonly moneyRequestsRepository: MoneyRequestsRepository,
private readonly juniorService: JuniorService,
private readonly ociService: OciService,
) {}
async createMoneyRequest(juniorId: string, body: CreateMoneyRequestDto) {
const junior = await this.juniorService.findJuniorById(juniorId);
const moneyRequest = await this.moneyRequestsRepository.createMoneyRequest(junior.id, junior.guardianId, body);
return this.findById(moneyRequest.id);
}
async findById(id: string, userId?: string, role?: Roles): Promise<MoneyRequest> {
const moneyRequest = await this.moneyRequestsRepository.findById(id, userId, role);
if (!moneyRequest) {
throw new BadRequestException('MONEY_REQUEST.NOT_FOUND');
}
await this.prepareJuniorImages([moneyRequest.junior]);
return moneyRequest;
}
async findMoneyRequests(
userId: string,
role: Roles,
filters: MoneyRequestsFiltersRequestDto,
): Promise<[MoneyRequest[], number]> {
const [moneyRequests, count] = await this.moneyRequestsRepository.findAll(userId, role, filters);
const juniors = moneyRequests.map((moneyRequest) => moneyRequest.junior);
await this.prepareJuniorImages(juniors);
return [moneyRequests, count];
}
@Transactional()
async approveMoneyRequest(id: string, guardianId: string): Promise<void> {
const moneyRequest = await this.moneyRequestsRepository.findById(id, guardianId, Roles.GUARDIAN);
if (!moneyRequest) {
throw new BadRequestException('MONEY_REQUEST.NOT_FOUND');
}
if (moneyRequest.status == MoneyRequestStatus.APPROVED) {
throw new BadRequestException('MONEY_REQUEST.ALREADY_APPROVED');
}
await Promise.all([
this.moneyRequestsRepository.approveMoneyRequest(id),
this.juniorService.transferToJunior(
moneyRequest.juniorId,
{ amount: moneyRequest.amount },
moneyRequest.guardianId,
),
]);
}
async rejectMoneyRequest(
id: string,
guardianId: string,
rejectionReasondto: RejectionMoneyRequestDto,
): Promise<void> {
const moneyRequest = await this.moneyRequestsRepository.findById(id, guardianId, Roles.GUARDIAN);
if (!moneyRequest) {
throw new BadRequestException('MONEY_REQUEST.NOT_FOUND');
}
if (moneyRequest.status == MoneyRequestStatus.APPROVED) {
throw new BadRequestException('MONEY_REQUEST.ALREADY_APPROVED');
}
if (moneyRequest.status == MoneyRequestStatus.REJECTED) {
throw new BadRequestException('MONEY_REQUEST.ALREADY_REJECTED');
}
await this.moneyRequestsRepository.rejectMoneyRequest(id, rejectionReasondto?.rejectionReason);
}
private async prepareJuniorImages(juniors: Junior[]) {
this.logger.log(`Preparing junior images`);
await Promise.all(
juniors.map(async (junior) => {
const profilePicture = junior.customer.user.profilePicture;
if (profilePicture) {
profilePicture.url = await this.ociService.generatePreSignedUrl(profilePicture);
}
}),
);
}
}

View File

@ -236,13 +236,18 @@ export class UserService {
throw new BadRequestException('USER.EMAIL_ALREADY_VERIFIED');
}
await this.otpService.verifyOtp({
const isOtpValid = await this.otpService.verifyOtp({
userId,
value: otp,
scope: OtpScope.VERIFY_EMAIL,
otpType: OtpType.EMAIL,
});
if (!isOtpValid) {
this.logger.error(`Invalid OTP for user with email ${user.email}`);
throw new BadRequestException('OTP.INVALID_OTP');
}
await this.userRepository.update(userId, { isEmailVerified: true });
this.logger.log(`Email for user ${userId} verified successfully`);
}