mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-11-26 00:24:54 +00:00
Compare commits
6 Commits
edddc2f457
...
e6642b5a15
| Author | SHA1 | Date | |
|---|---|---|---|
| e6642b5a15 | |||
| 954aa422a2 | |||
| 15a48e4884 | |||
| d768da70f2 | |||
| 9b0e1791da | |||
| 44b5937f7a |
@ -1,12 +1,14 @@
|
||||
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { Body, Controller, Get, HttpCode, HttpStatus, 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 } from '../dtos/responses';
|
||||
import { CardService } from '../services';
|
||||
|
||||
@Controller('cards')
|
||||
@ -36,4 +38,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);
|
||||
}
|
||||
}
|
||||
|
||||
9
src/card/dtos/requests/fund-iban.request.dto.ts
Normal file
9
src/card/dtos/requests/fund-iban.request.dto.ts
Normal 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;
|
||||
}
|
||||
1
src/card/dtos/requests/index.ts
Normal file
1
src/card/dtos/requests/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './fund-iban.request.dto';
|
||||
10
src/card/dtos/responses/account-iban.response.dto.ts
Normal file
10
src/card/dtos/responses/account-iban.response.dto.ts
Normal file
@ -0,0 +1,10 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class AccountIbanResponseDto {
|
||||
@ApiProperty({ example: 'DE89370400440532013000' })
|
||||
iban!: string;
|
||||
|
||||
constructor(iban: string) {
|
||||
this.iban = iban;
|
||||
}
|
||||
}
|
||||
@ -1 +1,2 @@
|
||||
export * from './account-iban.response.dto';
|
||||
export * from './card.response.dto';
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -60,4 +60,10 @@ export class CardRepository {
|
||||
statusDescription: statusDescription,
|
||||
});
|
||||
}
|
||||
|
||||
updateCardLimit(cardId: string, newLimit: number) {
|
||||
return this.cardRepository.update(cardId, {
|
||||
limit: newLimit,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Decimal } from 'decimal.js';
|
||||
import moment from 'moment';
|
||||
import { Repository } from 'typeorm';
|
||||
import {
|
||||
@ -57,9 +58,43 @@ 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 },
|
||||
});
|
||||
}
|
||||
|
||||
findInternalTransactionTotal(accountId: string): Promise<number> {
|
||||
return this.transactionRepository
|
||||
.find({
|
||||
where: { accountId, transactionType: TransactionType.INTERNAL },
|
||||
})
|
||||
.then((transactions) => {
|
||||
return transactions
|
||||
.reduce((total, tx) => new Decimal(total).plus(tx.transactionAmount), new Decimal(0))
|
||||
.toNumber();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -27,10 +27,26 @@ 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);
|
||||
/**
|
||||
@ -44,4 +60,10 @@ export class AccountService {
|
||||
|
||||
return this.accountRepository.decreaseAccountBalance(accountReference, 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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { BadRequestException, forwardRef, Inject, Injectable } 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';
|
||||
@ -10,12 +11,14 @@ 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 {
|
||||
constructor(
|
||||
private readonly cardRepository: CardRepository,
|
||||
private readonly accountService: AccountService,
|
||||
@Inject(forwardRef(() => TransactionService)) private readonly transactionService: TransactionService,
|
||||
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
||||
@Inject(forwardRef(() => CustomerService)) private readonly customerService: CustomerService,
|
||||
) {}
|
||||
@ -99,4 +102,40 @@ export class CardService {
|
||||
|
||||
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);
|
||||
const availableSpendingLimit = await this.transactionService.calculateAvailableSpendingLimitForParent(card.account);
|
||||
|
||||
if (amount > availableSpendingLimit) {
|
||||
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.transactionService.createInternalChildTransaction(card.id, amount),
|
||||
]);
|
||||
|
||||
return finalAmount.toNumber();
|
||||
}
|
||||
|
||||
fundIban(iban: string, amount: number) {
|
||||
return this.accountService.fundIban(iban, amount);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
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 {
|
||||
AccountTransactionWebhookRequest,
|
||||
CardTransactionWebhookRequest,
|
||||
} from '~/common/modules/neoleap/dtos/requests';
|
||||
import { Account } from '../entities/account.entity';
|
||||
import { Transaction } from '../entities/transaction.entity';
|
||||
import { TransactionRepository } from '../repositories/transaction.repository';
|
||||
import { AccountService } from './account.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()
|
||||
@ -51,6 +52,17 @@ 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;
|
||||
}
|
||||
|
||||
async calculateAvailableSpendingLimitForParent(account: Account): Promise<number> {
|
||||
const internalTransactionSum = await this.transactionRepository.findInternalTransactionTotal(account.id);
|
||||
return new Decimal(account.balance).minus(internalTransactionSum).toNumber();
|
||||
}
|
||||
|
||||
private async findExistingTransaction(transactionId: string, accountReference: string): Promise<Transaction | null> {
|
||||
const existingTransaction = await this.transactionRepository.findTransactionByReference(
|
||||
transactionId,
|
||||
|
||||
@ -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';
|
||||
|
||||
3
src/core/utils/patch.util.ts
Normal file
3
src/core/utils/patch.util.ts
Normal 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];
|
||||
};
|
||||
@ -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;
|
||||
|
||||
@ -67,7 +67,8 @@
|
||||
"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": {
|
||||
@ -102,5 +103,8 @@
|
||||
},
|
||||
"OTP": {
|
||||
"INVALID_OTP": "رمز التحقق الذي أدخلته غير صالح. يرجى المحاولة مرة أخرى."
|
||||
},
|
||||
"CARD": {
|
||||
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل."
|
||||
}
|
||||
}
|
||||
|
||||
@ -66,7 +66,8 @@
|
||||
"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": {
|
||||
@ -101,5 +102,8 @@
|
||||
},
|
||||
"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."
|
||||
}
|
||||
}
|
||||
|
||||
@ -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, UpdateJuniorRequestDto } 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')
|
||||
@ -100,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));
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,3 +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';
|
||||
|
||||
12
src/junior/dtos/request/transfer-to-junior.request.dto.ts
Normal file
12
src/junior/dtos/request/transfer-to-junior.request.dto.ts
Normal 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;
|
||||
}
|
||||
@ -1,6 +1,5 @@
|
||||
import { OmitType, PartialType } from '@nestjs/mapped-types';
|
||||
import { OmitType, PartialType } from '@nestjs/swagger';
|
||||
import { CreateJuniorRequestDto } from './create-junior.request.dto';
|
||||
|
||||
export class UpdateJuniorRequestDto extends PartialType(
|
||||
OmitType(CreateJuniorRequestDto, ['cardColor', 'cardPin'] as const),
|
||||
) {}
|
||||
const omitted = OmitType(CreateJuniorRequestDto, ['cardColor', 'cardPin']);
|
||||
export class UpdateJuniorRequestDto extends PartialType(omitted) {}
|
||||
|
||||
@ -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';
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
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' })
|
||||
@ -16,9 +17,18 @@ export class JuniorResponseDto {
|
||||
@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;
|
||||
|
||||
@ -27,7 +37,10 @@ export class JuniorResponseDto {
|
||||
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.profilePicture = junior.customer.user.profilePicture
|
||||
? new DocumentMetaResponseDto(junior.customer.user.profilePicture)
|
||||
: null;
|
||||
|
||||
10
src/junior/dtos/response/transfer-to-junior.response.dto.ts
Normal file
10
src/junior/dtos/response/transfer-to-junior.response.dto.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
@ -4,12 +4,18 @@ 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 { UserType } from '~/user/enums';
|
||||
import { UserService } from '~/user/services';
|
||||
import { UserTokenService } from '~/user/services/user-token.service';
|
||||
import { CreateJuniorRequestDto, SetThemeRequestDto, UpdateJuniorRequestDto } from '../dtos/request';
|
||||
import {
|
||||
CreateJuniorRequestDto,
|
||||
SetThemeRequestDto,
|
||||
TransferToJuniorRequestDto,
|
||||
UpdateJuniorRequestDto,
|
||||
} from '../dtos/request';
|
||||
import { Junior } from '../entities';
|
||||
import { JuniorRepository } from '../repositories';
|
||||
import { QrcodeService } from './qrcode.service';
|
||||
@ -88,17 +94,14 @@ export class JuniorService {
|
||||
async updateJunior(juniorId: string, body: UpdateJuniorRequestDto, guardianId: string) {
|
||||
this.logger.log(`Updating junior ${juniorId}`);
|
||||
const junior = await this.findJuniorById(juniorId, false, guardianId);
|
||||
if (body.profilePictureId) {
|
||||
junior.customer.user.profilePictureId = body.profilePictureId;
|
||||
}
|
||||
if (body.firstName) {
|
||||
junior.customer.user.firstName = body.firstName;
|
||||
junior.customer.firstName = body.firstName;
|
||||
}
|
||||
if (body.lastName) {
|
||||
junior.customer.user.lastName = body.lastName;
|
||||
junior.customer.lastName = body.lastName;
|
||||
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) {
|
||||
@ -107,16 +110,16 @@ export class JuniorService {
|
||||
}
|
||||
junior.customer.user.email = body.email;
|
||||
}
|
||||
setIf(user, 'profilePictureId', body.profilePictureId);
|
||||
setIf(user, 'firstName', body.firstName);
|
||||
setIf(user, 'lastName', body.lastName);
|
||||
|
||||
if (body.dateOfBirth) {
|
||||
junior.customer.dateOfBirth = body.dateOfBirth;
|
||||
}
|
||||
if (body.relationship) {
|
||||
junior.relationship = body.relationship;
|
||||
}
|
||||
console.log('++++++');
|
||||
setIf(customer, 'firstName', body.firstName);
|
||||
setIf(customer, 'lastName', body.lastName);
|
||||
setIf(customer, 'dateOfBirth', body.dateOfBirth as unknown as Date);
|
||||
|
||||
await Promise.all([junior.save(), junior.customer.user.save(), junior.customer.save()]);
|
||||
setIf(junior, 'relationship', body.relationship);
|
||||
await Promise.all([junior.save(), customer.save(), user.save()]);
|
||||
this.logger.log(`Junior ${juniorId} updated successfully`);
|
||||
return junior;
|
||||
}
|
||||
@ -169,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(
|
||||
|
||||
Reference in New Issue
Block a user