mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-11-26 00:24:54 +00:00
Compare commits
8 Commits
11712bedf3
...
44124b9964
| Author | SHA1 | Date | |
|---|---|---|---|
| 44124b9964 | |||
| 454ded627f | |||
| f1484e125b | |||
| df4d2e3c1f | |||
| 872d231f72 | |||
| cc4c8254f6 | |||
| 039c95aa56 | |||
| e1f50decfa |
@ -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
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, HttpCode, HttpStatus, Post, UseGuards } from '@nestjs/common';
|
||||
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';
|
||||
@ -8,7 +8,7 @@ import { CardEmbossingDetailsResponseDto } from '~/common/modules/neoleap/dtos/r
|
||||
import { ApiDataResponse } from '~/core/decorators';
|
||||
import { ResponseFactory } from '~/core/utils';
|
||||
import { FundIbanRequestDto } from '../dtos/requests';
|
||||
import { AccountIbanResponseDto, CardResponseDto } from '../dtos/responses';
|
||||
import { AccountIbanResponseDto, CardResponseDto, ChildCardResponseDto } from '../dtos/responses';
|
||||
import { CardService } from '../services';
|
||||
|
||||
@Controller('cards')
|
||||
@ -25,6 +25,33 @@ 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/:childid')
|
||||
@UseGuards(RolesGuard)
|
||||
@AllowedRoles(Roles.GUARDIAN)
|
||||
@ApiDataResponse(ChildCardResponseDto)
|
||||
async getChildCardById(@Param('childid') childId: string, @AuthenticatedUser() { sub }: IJwtPayload) {
|
||||
const card = await this.cardService.getCardByChildId(sub, childId);
|
||||
return ResponseFactory.data(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) {
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
48
src/card/dtos/responses/child-card.response.dto.ts
Normal file
48
src/card/dtos/responses/child-card.response.dto.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
@ -1,2 +1,3 @@
|
||||
export * from './account-iban.response.dto';
|
||||
export * from './card.response.dto';
|
||||
export * from './child-card.response.dto';
|
||||
|
||||
@ -22,9 +22,30 @@ export class Account {
|
||||
@Column('varchar', { length: 255, nullable: false, name: 'currency' })
|
||||
currency!: string;
|
||||
|
||||
@Column('decimal', { precision: 10, scale: 2, default: 0.0, name: 'balance' })
|
||||
@Column('decimal', {
|
||||
precision: 10,
|
||||
scale: 2,
|
||||
default: 0.0,
|
||||
name: 'balance',
|
||||
transformer: {
|
||||
to: (value: number) => value,
|
||||
from: (value: string) => parseFloat(value),
|
||||
},
|
||||
})
|
||||
balance!: number;
|
||||
|
||||
@Column('decimal', {
|
||||
precision: 10,
|
||||
scale: 2,
|
||||
default: 0.0,
|
||||
name: 'reserved_balance',
|
||||
transformer: {
|
||||
to: (value: number) => value,
|
||||
from: (value: string) => parseFloat(value),
|
||||
},
|
||||
})
|
||||
reservedBalance!: number;
|
||||
|
||||
@OneToMany(() => Card, (card) => card.account, { cascade: true })
|
||||
cards!: Card[];
|
||||
|
||||
|
||||
@ -55,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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,13 +14,14 @@ export class CardRepository {
|
||||
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: cardColor ? cardColor : CardColors.DEEP_MAGENTA,
|
||||
@ -28,14 +29,29 @@ export class CardRepository {
|
||||
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'] });
|
||||
}
|
||||
|
||||
findCardByChildId(guardianId: string, childId: string): Promise<Card | null> {
|
||||
return this.cardRepository.findOne({
|
||||
where: { parentId: guardianId, customerId: childId, customerType: CustomerType.CHILD },
|
||||
relations: ['account', 'customer', 'customer.user', 'customer.user.profilePicture', 'customer.junior'],
|
||||
});
|
||||
}
|
||||
|
||||
getCardByReferenceNumber(referenceNumber: string): Promise<Card | null> {
|
||||
return this.cardRepository.findOne({ where: { cardReference: referenceNumber }, relations: ['account'] });
|
||||
}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Decimal } from 'decimal.js';
|
||||
import moment from 'moment';
|
||||
import { Repository } from 'typeorm';
|
||||
import {
|
||||
@ -85,16 +84,4 @@ export class TransactionRepository {
|
||||
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();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -49,9 +49,11 @@ export class AccountService {
|
||||
|
||||
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) {
|
||||
@ -61,6 +63,17 @@ export class AccountService {
|
||||
return this.accountRepository.decreaseAccountBalance(accountReference, amount);
|
||||
}
|
||||
|
||||
increaseReservedBalance(account: Account, amount: number) {
|
||||
if (account.balance < account.reservedBalance + amount) {
|
||||
throw new UnprocessableEntityException('CARD.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);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
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';
|
||||
@ -6,6 +6,7 @@ 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';
|
||||
@ -15,9 +16,11 @@ 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,
|
||||
@ -42,6 +45,12 @@ 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(
|
||||
@ -49,10 +58,20 @@ export class CardService {
|
||||
parentCustomer.cards[0].account.id,
|
||||
data,
|
||||
cardColor,
|
||||
parentCustomer.id,
|
||||
);
|
||||
|
||||
return this.getCardById(createdCard.id);
|
||||
}
|
||||
|
||||
async getCardByChildId(guardianId: string, childId: string): Promise<Card> {
|
||||
const card = await this.cardRepository.findCardByChildId(guardianId, childId);
|
||||
if (!card) {
|
||||
throw new BadRequestException('CARD.NOT_FOUND');
|
||||
}
|
||||
await this.prepareJuniorImages([card]);
|
||||
return card;
|
||||
}
|
||||
async getCardById(id: string): Promise<Card> {
|
||||
const card = await this.cardRepository.getCardById(id);
|
||||
|
||||
@ -87,6 +106,7 @@ export class CardService {
|
||||
if (!card) {
|
||||
throw new BadRequestException('CARD.NOT_FOUND');
|
||||
}
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
@ -103,6 +123,14 @@ 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);
|
||||
|
||||
@ -119,9 +147,8 @@ export class CardService {
|
||||
@Transactional()
|
||||
async transferToChild(juniorId: string, amount: number) {
|
||||
const card = await this.getCardByCustomerId(juniorId);
|
||||
const availableSpendingLimit = await this.transactionService.calculateAvailableSpendingLimitForParent(card.account);
|
||||
|
||||
if (amount > availableSpendingLimit) {
|
||||
if (amount > card.account.balance - card.account.reservedBalance) {
|
||||
throw new BadRequestException('CARD.INSUFFICIENT_BALANCE');
|
||||
}
|
||||
|
||||
@ -129,6 +156,7 @@ export class CardService {
|
||||
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),
|
||||
]);
|
||||
|
||||
@ -138,4 +166,17 @@ export class CardService {
|
||||
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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,8 +5,8 @@ import {
|
||||
AccountTransactionWebhookRequest,
|
||||
CardTransactionWebhookRequest,
|
||||
} from '~/common/modules/neoleap/dtos/requests';
|
||||
import { Account } from '../entities/account.entity';
|
||||
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';
|
||||
@ -31,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);
|
||||
|
||||
await this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber());
|
||||
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;
|
||||
}
|
||||
@ -58,11 +65,6 @@ export class TransactionService {
|
||||
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,
|
||||
|
||||
@ -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"`);
|
||||
}
|
||||
}
|
||||
@ -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"`);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,13 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddDeletedAtColumnToJunior1757915357218 implements MigrationInterface {
|
||||
name = 'AddDeletedAtColumnToJunior1757915357218';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE "juniors" ADD "deleted_at" TIMESTAMP WITH TIME ZONE`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE "juniors" DROP COLUMN "deleted_at"`);
|
||||
}
|
||||
}
|
||||
@ -1,3 +1,6 @@
|
||||
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';
|
||||
export * from './1757915357218-add-deleted-at-column-to-junior';
|
||||
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -68,16 +68,14 @@
|
||||
"CIVIL_ID_REQUIRED": "مطلوب بطاقة الهوية المدنية.",
|
||||
"CIVIL_ID_NOT_CREATED_BY_GUARDIAN": "تم تحميل بطاقة الهوية المدنية من قبل شخص آخر غير ولي الأمر.",
|
||||
"CIVIL_ID_ALREADY_EXISTS": "بطاقة الهوية المدنية مستخدمة بالفعل من قبل طفل آخر.",
|
||||
"CANNOT_UPDATE_REGISTERED_USER": "الطفل قد سجل بالفعل. لا يُسمح بتحديث البيانات."
|
||||
"CANNOT_UPDATE_REGISTERED_USER": "الطفل قد سجل بالفعل. لا يُسمح بتحديث البيانات.",
|
||||
"CANNOT_DELETE_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": {
|
||||
@ -103,8 +101,10 @@
|
||||
},
|
||||
"OTP": {
|
||||
"INVALID_OTP": "رمز التحقق الذي أدخلته غير صالح. يرجى المحاولة مرة أخرى."
|
||||
},
|
||||
"CARD": {
|
||||
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل."
|
||||
},
|
||||
"CARD": {
|
||||
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
|
||||
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر.",
|
||||
"NOT_FOUND": "لم يتم العثور على البطاقة."
|
||||
}
|
||||
}
|
||||
|
||||
@ -67,16 +67,14 @@
|
||||
"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.",
|
||||
"CANNOT_UPDATE_REGISTERED_USER": "The junior has already registered. Updating details is not allowed."
|
||||
"CANNOT_UPDATE_REGISTERED_USER": "The junior has already registered. Updating details is not allowed.",
|
||||
"CANNOT_DELETE_REGISTERED_USER": "The junior has already registered. Deleting the junior 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": {
|
||||
@ -104,6 +102,8 @@
|
||||
"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."
|
||||
"INSUFFICIENT_BALANCE": "The card does not have sufficient balance to complete this transfer.",
|
||||
"DOES_NOT_BELONG_TO_GUARDIAN": "The card does not belong to the guardian.",
|
||||
"NOT_FOUND": "The card was not found."
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,16 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
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';
|
||||
@ -83,6 +95,14 @@ export class JuniorController {
|
||||
return ResponseFactory.data(new JuniorResponseDto(junior));
|
||||
}
|
||||
|
||||
@Delete(':juniorId')
|
||||
@UseGuards(RolesGuard)
|
||||
@AllowedRoles(Roles.GUARDIAN)
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async deleteJunior(@AuthenticatedUser() user: IJwtPayload, @Param('juniorId', CustomParseUUIDPipe) juniorId: string) {
|
||||
await this.juniorService.deleteJunior(juniorId, user.sub);
|
||||
}
|
||||
|
||||
@Post('set-theme')
|
||||
@UseGuards(RolesGuard)
|
||||
@AllowedRoles(Roles.JUNIOR)
|
||||
|
||||
@ -32,7 +32,11 @@ export class JuniorResponseDto {
|
||||
@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.firstName = junior.customer.firstName;
|
||||
this.lastName = junior.customer.lastName;
|
||||
@ -41,6 +45,7 @@ export class JuniorResponseDto {
|
||||
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;
|
||||
|
||||
@ -2,15 +2,18 @@ import {
|
||||
BaseEntity,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
DeleteDateColumn,
|
||||
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,9 +42,15 @@ 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;
|
||||
|
||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||
updatedAt!: Date;
|
||||
|
||||
@DeleteDateColumn({ name: 'deleted_at', type: 'timestamp with time zone', nullable: true })
|
||||
deletedAt!: Date | null;
|
||||
}
|
||||
|
||||
@ -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', 'customer.user.profilePicture'];
|
||||
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');
|
||||
}
|
||||
@ -51,4 +65,8 @@ export class JuniorRepository {
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
softDelete(juniorId: string) {
|
||||
return this.juniorRepository.softDelete({ id: juniorId });
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||
import { IsNull, Not } from 'typeorm';
|
||||
import { Transactional } from 'typeorm-transactional';
|
||||
import { Roles } from '~/auth/enums';
|
||||
import { CardService } from '~/card/services';
|
||||
@ -183,6 +184,31 @@ export class JuniorService {
|
||||
return this.cardService.transferToChild(juniorId, body.amount);
|
||||
}
|
||||
|
||||
async deleteJunior(juniorId: string, 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');
|
||||
}
|
||||
|
||||
const hasPassword = await this.userService.findUser({ id: juniorId, password: Not(IsNull()) });
|
||||
|
||||
if (hasPassword) {
|
||||
this.logger.error(`Cannot delete junior ${juniorId} with registered user`);
|
||||
throw new BadRequestException('JUNIOR.CANNOT_DELETE_REGISTERED_USER');
|
||||
}
|
||||
|
||||
const { affected } = await this.juniorRepository.softDelete(juniorId);
|
||||
|
||||
if (affected === 0) {
|
||||
this.logger.error(`Junior ${juniorId} not found`);
|
||||
throw new BadRequestException('JUNIOR.NOT_FOUND');
|
||||
}
|
||||
|
||||
this.logger.log(`Junior ${juniorId} deleted successfully`);
|
||||
}
|
||||
|
||||
private async prepareJuniorImages(juniors: Junior[]) {
|
||||
this.logger.log(`Preparing junior images`);
|
||||
await Promise.all(
|
||||
|
||||
1
src/money-request/controllers/index.ts
Normal file
1
src/money-request/controllers/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './money-requests.controller';
|
||||
81
src/money-request/controllers/money-requests.controller.ts
Normal file
81
src/money-request/controllers/money-requests.controller.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
3
src/money-request/dtos/request/index.ts
Normal file
3
src/money-request/dtos/request/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export * from './create-money-request.request.dto';
|
||||
export * from './money-requests-filters.request.dto';
|
||||
export * from './rejection.request.dto';
|
||||
@ -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;
|
||||
}
|
||||
9
src/money-request/dtos/request/rejection.request.dto.ts
Normal file
9
src/money-request/dtos/request/rejection.request.dto.ts
Normal 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;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
51
src/money-request/entities/money-request.entity.ts
Normal file
51
src/money-request/entities/money-request.entity.ts
Normal 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;
|
||||
}
|
||||
1
src/money-request/enums/index.ts
Normal file
1
src/money-request/enums/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './money-request-status.enum';
|
||||
5
src/money-request/enums/money-request-status.enum.ts
Normal file
5
src/money-request/enums/money-request-status.enum.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export enum MoneyRequestStatus {
|
||||
PENDING = 'PENDING',
|
||||
APPROVED = 'APPROVED',
|
||||
REJECTED = 'REJECTED',
|
||||
}
|
||||
14
src/money-request/money-request.module.ts
Normal file
14
src/money-request/money-request.module.ts
Normal 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 {}
|
||||
1
src/money-request/repositories/index.ts
Normal file
1
src/money-request/repositories/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './money-requests.repository';
|
||||
70
src/money-request/repositories/money-requests.repository.ts
Normal file
70
src/money-request/repositories/money-requests.repository.ts
Normal 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 });
|
||||
}
|
||||
}
|
||||
1
src/money-request/services/index.ts
Normal file
1
src/money-request/services/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './money-requests.service';
|
||||
102
src/money-request/services/money-requests.service.ts
Normal file
102
src/money-request/services/money-requests.service.ts
Normal 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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user