mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-11-26 16:44:54 +00:00
Compare commits
48 Commits
7dd309e0e3
...
ZOD-349-we
| Author | SHA1 | Date | |
|---|---|---|---|
| 05a6ad2d84 | |||
| bbeece9e03 | |||
| 596562f6dc | |||
| 10de8f69c9 | |||
| 8a6b1cc900 | |||
| d16ae66252 | |||
| e966f95463 | |||
| 2714255dd1 | |||
| 39a0b131b8 | |||
| 4f778f7904 | |||
| 7e9bc397a9 | |||
| 7bfc14f0d9 | |||
| d2e084d3e4 | |||
| f81714a525 | |||
| f3282a680b | |||
| 7b57277a7f | |||
| fdd2e23669 | |||
| d70ab09960 | |||
| 297a2fe5ad | |||
| 33b4f13ec8 | |||
| 310233c519 | |||
| 15621124ad | |||
| 7fc1918de0 | |||
| f6fa74897a | |||
| dd6886ff2b | |||
| 649191f3f4 | |||
| 183f6b4475 | |||
| 8f601b26ae | |||
| 918b15c315 | |||
| 1830d92cbd | |||
| 44124b9964 | |||
| 454ded627f | |||
| f1484e125b | |||
| df4d2e3c1f | |||
| 872d231f72 | |||
| cc4c8254f6 | |||
| 039c95aa56 | |||
| e1f50decfa | |||
| 11712bedf3 | |||
| e6642b5a15 | |||
| 954aa422a2 | |||
| 15a48e4884 | |||
| d768da70f2 | |||
| 9b0e1791da | |||
| 44b5937f7a | |||
| edddc2f457 | |||
| 88730a2b2b | |||
| 3df34c0017 |
@ -28,6 +28,7 @@ import { HealthModule } from './health/health.module';
|
|||||||
import { JuniorModule } from './junior/junior.module';
|
import { JuniorModule } from './junior/junior.module';
|
||||||
import { UserModule } from './user/user.module';
|
import { UserModule } from './user/user.module';
|
||||||
import { WebhookModule } from './webhook/webhook.module';
|
import { WebhookModule } from './webhook/webhook.module';
|
||||||
|
import { MoneyRequestModule } from './money-request/money-request.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
controllers: [],
|
controllers: [],
|
||||||
@ -74,6 +75,7 @@ import { WebhookModule } from './webhook/webhook.module';
|
|||||||
CronModule,
|
CronModule,
|
||||||
NeoLeapModule,
|
NeoLeapModule,
|
||||||
WebhookModule,
|
WebhookModule,
|
||||||
|
MoneyRequestModule,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
// Global Pipes
|
// Global Pipes
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { Gender } from '~/customer/enums';
|
||||||
import { DocumentMetaResponseDto } from '~/document/dtos/response';
|
import { DocumentMetaResponseDto } from '~/document/dtos/response';
|
||||||
import { User } from '~/user/entities';
|
import { User } from '~/user/entities';
|
||||||
|
|
||||||
@ -33,6 +34,10 @@ export class UserResponseDto {
|
|||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
isEmailVerified!: boolean;
|
isEmailVerified!: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: Gender, nullable: true })
|
||||||
|
gender!: Gender | null;
|
||||||
|
|
||||||
|
|
||||||
constructor(user: User) {
|
constructor(user: User) {
|
||||||
this.id = user.id;
|
this.id = user.id;
|
||||||
this.countryCode = user.countryCode;
|
this.countryCode = user.countryCode;
|
||||||
@ -44,5 +49,6 @@ export class UserResponseDto {
|
|||||||
this.profilePicture = user.profilePicture ? new DocumentMetaResponseDto(user.profilePicture) : null;
|
this.profilePicture = user.profilePicture ? new DocumentMetaResponseDto(user.profilePicture) : null;
|
||||||
this.isEmailVerified = user.isEmailVerified;
|
this.isEmailVerified = user.isEmailVerified;
|
||||||
this.isPhoneVerified = user.isPhoneVerified;
|
this.isPhoneVerified = user.isPhoneVerified;
|
||||||
|
this.gender = (user.customer?.gender as Gender) || null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,12 +1,14 @@
|
|||||||
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Get, HttpCode, HttpStatus, Param, Post, UseGuards } from '@nestjs/common';
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { Roles } from '~/auth/enums';
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
import { IJwtPayload } from '~/auth/interfaces';
|
||||||
import { AuthenticatedUser } from '~/common/decorators';
|
import { AllowedRoles, AuthenticatedUser } from '~/common/decorators';
|
||||||
import { AccessTokenGuard } from '~/common/guards';
|
import { AccessTokenGuard, RolesGuard } from '~/common/guards';
|
||||||
import { CardEmbossingDetailsResponseDto } from '~/common/modules/neoleap/dtos/response';
|
import { CardEmbossingDetailsResponseDto } from '~/common/modules/neoleap/dtos/response';
|
||||||
import { ApiDataResponse } from '~/core/decorators';
|
import { ApiDataResponse } from '~/core/decorators';
|
||||||
import { ResponseFactory } from '~/core/utils';
|
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';
|
import { CardService } from '../services';
|
||||||
|
|
||||||
@Controller('cards')
|
@Controller('cards')
|
||||||
@ -23,6 +25,33 @@ export class CardsController {
|
|||||||
return ResponseFactory.data(new CardResponseDto(card));
|
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')
|
@Get('current')
|
||||||
@ApiDataResponse(CardResponseDto)
|
@ApiDataResponse(CardResponseDto)
|
||||||
async getCurrentCard(@AuthenticatedUser() { sub }: IJwtPayload) {
|
async getCurrentCard(@AuthenticatedUser() { sub }: IJwtPayload) {
|
||||||
@ -36,4 +65,22 @@ export class CardsController {
|
|||||||
const res = await this.cardService.getEmbossingInformation(sub);
|
const res = await this.cardService.getEmbossingInformation(sub);
|
||||||
return ResponseFactory.data(res);
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -43,6 +43,13 @@ export class CardResponseDto {
|
|||||||
})
|
})
|
||||||
balance!: number;
|
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) {
|
constructor(card: Card) {
|
||||||
this.id = card.id;
|
this.id = card.id;
|
||||||
this.firstSixDigits = card.firstSixDigits;
|
this.firstSixDigits = card.firstSixDigits;
|
||||||
@ -51,6 +58,9 @@ export class CardResponseDto {
|
|||||||
this.status = card.status;
|
this.status = card.status;
|
||||||
this.statusDescription = CardStatusDescriptionMapper[card.statusDescription][UserLocale.ENGLISH].description;
|
this.statusDescription = CardStatusDescriptionMapper[card.statusDescription][UserLocale.ENGLISH].description;
|
||||||
this.balance =
|
this.balance =
|
||||||
card.customerType === CustomerType.CHILD ? Math.min(card.limit, card.account.balance) : card.account.balance;
|
card.customerType === CustomerType.CHILD
|
||||||
|
? Math.min(card.limit, card.account.balance)
|
||||||
|
: card.account.balance - card.account.reservedBalance;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
16
src/card/dtos/responses/child-transfer-item.response.dto.ts
Normal file
16
src/card/dtos/responses/child-transfer-item.response.dto.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class ChildTransferItemDto {
|
||||||
|
@ApiProperty({ example: '2025-10-14T09:53:40.000Z' })
|
||||||
|
date!: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 50.0 })
|
||||||
|
amount!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'SAR' })
|
||||||
|
currency!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'You received {{amount}} {{currency}} from your parent.' })
|
||||||
|
message!: string;
|
||||||
|
}
|
||||||
|
|
||||||
17
src/card/dtos/responses/guardian-home.response.dto.ts
Normal file
17
src/card/dtos/responses/guardian-home.response.dto.ts
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { TransactionItemResponseDto } from './transaction-item.response.dto';
|
||||||
|
|
||||||
|
export class GuardianHomeResponseDto {
|
||||||
|
@ApiProperty({ example: 2000.0 })
|
||||||
|
availableBalance!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ type: [TransactionItemResponseDto] })
|
||||||
|
recentTransactions!: TransactionItemResponseDto[];
|
||||||
|
|
||||||
|
constructor(availableBalance: number, recentTransactions: TransactionItemResponseDto[]) {
|
||||||
|
this.availableBalance = availableBalance;
|
||||||
|
this.recentTransactions = recentTransactions;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -1 +1,15 @@
|
|||||||
|
export * from './account-iban.response.dto';
|
||||||
export * from './card.response.dto';
|
export * from './card.response.dto';
|
||||||
|
export * from './child-card.response.dto';
|
||||||
|
export * from './transaction-item.response.dto';
|
||||||
|
export * from './guardian-home.response.dto';
|
||||||
|
export * from './paged-transactions.response.dto';
|
||||||
|
export * from './parent-transfer-item.response.dto';
|
||||||
|
export * from './parent-home.response.dto';
|
||||||
|
export * from './paged-parent-transfers.response.dto';
|
||||||
|
export * from './child-transfer-item.response.dto';
|
||||||
|
export * from './junior-home.response.dto';
|
||||||
|
export * from './paged-child-transfers.response.dto';
|
||||||
|
export * from './spending-history-item.response.dto';
|
||||||
|
export * from './spending-history.response.dto';
|
||||||
|
export * from './transaction-detail.response.dto';
|
||||||
|
|||||||
16
src/card/dtos/responses/junior-home.response.dto.ts
Normal file
16
src/card/dtos/responses/junior-home.response.dto.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { ChildTransferItemDto } from './child-transfer-item.response.dto';
|
||||||
|
|
||||||
|
export class JuniorHomeResponseDto {
|
||||||
|
@ApiProperty({ example: 500.0 })
|
||||||
|
availableBalance!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ type: [ChildTransferItemDto] })
|
||||||
|
recentTransfers!: ChildTransferItemDto[];
|
||||||
|
|
||||||
|
constructor(availableBalance: number, recentTransfers: ChildTransferItemDto[]) {
|
||||||
|
this.availableBalance = availableBalance;
|
||||||
|
this.recentTransfers = recentTransfers;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,33 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { ChildTransferItemDto } from './child-transfer-item.response.dto';
|
||||||
|
|
||||||
|
export class PagedChildTransfersResponseDto {
|
||||||
|
@ApiProperty({ type: [ChildTransferItemDto] })
|
||||||
|
items!: ChildTransferItemDto[];
|
||||||
|
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
page!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 10 })
|
||||||
|
size!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 20 })
|
||||||
|
total!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: true })
|
||||||
|
hasMore!: boolean;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
items: ChildTransferItemDto[],
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
total: number,
|
||||||
|
) {
|
||||||
|
this.items = items;
|
||||||
|
this.page = page;
|
||||||
|
this.size = size;
|
||||||
|
this.total = total;
|
||||||
|
this.hasMore = page * size < total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,33 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { ParentTransferItemDto } from './parent-transfer-item.response.dto';
|
||||||
|
|
||||||
|
export class PagedParentTransfersResponseDto {
|
||||||
|
@ApiProperty({ type: [ParentTransferItemDto] })
|
||||||
|
items!: ParentTransferItemDto[];
|
||||||
|
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
page!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 10 })
|
||||||
|
size!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 45 })
|
||||||
|
total!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: true })
|
||||||
|
hasMore!: boolean;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
items: ParentTransferItemDto[],
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
total: number,
|
||||||
|
) {
|
||||||
|
this.items = items;
|
||||||
|
this.page = page;
|
||||||
|
this.size = size;
|
||||||
|
this.total = total;
|
||||||
|
this.hasMore = page * size < total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
33
src/card/dtos/responses/paged-transactions.response.dto.ts
Normal file
33
src/card/dtos/responses/paged-transactions.response.dto.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { TransactionItemResponseDto } from './transaction-item.response.dto';
|
||||||
|
|
||||||
|
export class PagedTransactionsResponseDto {
|
||||||
|
@ApiProperty({ type: [TransactionItemResponseDto] })
|
||||||
|
items!: TransactionItemResponseDto[];
|
||||||
|
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
page!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 10 })
|
||||||
|
size!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 45 })
|
||||||
|
total!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: true })
|
||||||
|
hasMore!: boolean;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
items: TransactionItemResponseDto[],
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
total: number,
|
||||||
|
) {
|
||||||
|
this.items = items;
|
||||||
|
this.page = page;
|
||||||
|
this.size = size;
|
||||||
|
this.total = total;
|
||||||
|
this.hasMore = page * size < total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
16
src/card/dtos/responses/parent-home.response.dto.ts
Normal file
16
src/card/dtos/responses/parent-home.response.dto.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { ParentTransferItemDto } from './parent-transfer-item.response.dto';
|
||||||
|
|
||||||
|
export class ParentHomeResponseDto {
|
||||||
|
@ApiProperty({ example: 2000.0 })
|
||||||
|
availableBalance!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ type: [ParentTransferItemDto] })
|
||||||
|
recentTransfers!: ParentTransferItemDto[];
|
||||||
|
|
||||||
|
constructor(availableBalance: number, recentTransfers: ParentTransferItemDto[]) {
|
||||||
|
this.availableBalance = availableBalance;
|
||||||
|
this.recentTransfers = recentTransfers;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
16
src/card/dtos/responses/parent-transfer-item.response.dto.ts
Normal file
16
src/card/dtos/responses/parent-transfer-item.response.dto.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class ParentTransferItemDto {
|
||||||
|
@ApiProperty({ example: '2025-10-14T09:53:40.000Z' })
|
||||||
|
date!: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 50.0 })
|
||||||
|
amount!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'SAR' })
|
||||||
|
currency!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Ahmed Ali' })
|
||||||
|
childName!: string;
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,58 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { Transaction } from '~/card/entities/transaction.entity';
|
||||||
|
|
||||||
|
export class SpendingHistoryItemDto {
|
||||||
|
@ApiProperty({ example: '2025-10-14T09:53:40.000Z' })
|
||||||
|
date!: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 50.5 })
|
||||||
|
amount!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'SAR' })
|
||||||
|
currency!: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Shopping' })
|
||||||
|
category!: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Target Store' })
|
||||||
|
merchantName!: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Riyadh' })
|
||||||
|
merchantCity!: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '277012*****3456' })
|
||||||
|
cardMasked!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
transactionId!: string;
|
||||||
|
|
||||||
|
constructor(transaction: Transaction) {
|
||||||
|
this.date = transaction.transactionDate;
|
||||||
|
this.amount = transaction.transactionAmount;
|
||||||
|
this.currency = transaction.transactionCurrency === '682' ? 'SAR' : transaction.transactionCurrency;
|
||||||
|
this.category = this.mapMccToCategory(transaction.merchantCategoryCode);
|
||||||
|
this.merchantName = transaction.merchantName;
|
||||||
|
this.merchantCity = transaction.merchantCity;
|
||||||
|
this.cardMasked = transaction.cardMaskedNumber;
|
||||||
|
this.transactionId = transaction.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapMccToCategory(mcc: string | null): string {
|
||||||
|
if (!mcc) return 'Other';
|
||||||
|
|
||||||
|
const mccCode = mcc;
|
||||||
|
|
||||||
|
// Map MCC codes to categories
|
||||||
|
if (mccCode >= '5200' && mccCode <= '5599') return 'Shopping';
|
||||||
|
if (mccCode >= '5800' && mccCode <= '5899') return 'Food & Dining';
|
||||||
|
if (mccCode >= '3000' && mccCode <= '3999') return 'Travel';
|
||||||
|
if (mccCode >= '4000' && mccCode <= '4799') return 'Transportation';
|
||||||
|
if (mccCode >= '7200' && mccCode <= '7999') return 'Entertainment';
|
||||||
|
if (mccCode >= '5900' && mccCode <= '5999') return 'Services';
|
||||||
|
if (mccCode >= '4800' && mccCode <= '4899') return 'Utilities';
|
||||||
|
if (mccCode >= '8000' && mccCode <= '8999') return 'Health & Wellness';
|
||||||
|
|
||||||
|
return 'Other';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
24
src/card/dtos/responses/spending-history.response.dto.ts
Normal file
24
src/card/dtos/responses/spending-history.response.dto.ts
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { SpendingHistoryItemDto } from './spending-history-item.response.dto';
|
||||||
|
|
||||||
|
export class SpendingHistoryResponseDto {
|
||||||
|
@ApiProperty({ type: [SpendingHistoryItemDto] })
|
||||||
|
transactions!: SpendingHistoryItemDto[];
|
||||||
|
|
||||||
|
@ApiProperty({ example: 150.75 })
|
||||||
|
totalSpent!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'SAR' })
|
||||||
|
currency!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 10 })
|
||||||
|
count!: number;
|
||||||
|
|
||||||
|
constructor(transactions: SpendingHistoryItemDto[], currency: string = 'SAR') {
|
||||||
|
this.transactions = transactions;
|
||||||
|
this.totalSpent = transactions.reduce((sum, tx) => sum + tx.amount, 0);
|
||||||
|
this.currency = currency;
|
||||||
|
this.count = transactions.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
74
src/card/dtos/responses/transaction-detail.response.dto.ts
Normal file
74
src/card/dtos/responses/transaction-detail.response.dto.ts
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { Transaction } from '~/card/entities/transaction.entity';
|
||||||
|
|
||||||
|
export class TransactionDetailResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
id!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2025-10-14T09:53:40.000Z' })
|
||||||
|
date!: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 50.5 })
|
||||||
|
amount!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'SAR' })
|
||||||
|
currency!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 2.5 })
|
||||||
|
fees!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 0.5 })
|
||||||
|
vatOnFees!: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Target Store' })
|
||||||
|
merchantName!: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Shopping' })
|
||||||
|
category!: string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'Riyadh' })
|
||||||
|
merchantCity!: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '277012*****3456' })
|
||||||
|
cardMasked!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
rrn!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
transactionId!: string;
|
||||||
|
|
||||||
|
constructor(transaction: Transaction) {
|
||||||
|
this.id = transaction.id;
|
||||||
|
this.date = transaction.transactionDate;
|
||||||
|
this.amount = transaction.transactionAmount;
|
||||||
|
this.currency = transaction.transactionCurrency === '682' ? 'SAR' : transaction.transactionCurrency;
|
||||||
|
this.fees = transaction.fees;
|
||||||
|
this.vatOnFees = transaction.vatOnFees;
|
||||||
|
this.merchantName = transaction.merchantName;
|
||||||
|
this.category = this.mapMccToCategory(transaction.merchantCategoryCode);
|
||||||
|
this.merchantCity = transaction.merchantCity;
|
||||||
|
this.cardMasked = transaction.cardMaskedNumber;
|
||||||
|
this.rrn = transaction.rrn;
|
||||||
|
this.transactionId = transaction.transactionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapMccToCategory(mcc: string | null): string {
|
||||||
|
if (!mcc) return 'Other';
|
||||||
|
|
||||||
|
const mccCode = mcc;
|
||||||
|
|
||||||
|
// Map MCC codes to categories
|
||||||
|
if (mccCode >= '5200' && mccCode <= '5599') return 'Shopping';
|
||||||
|
if (mccCode >= '5800' && mccCode <= '5899') return 'Food & Dining';
|
||||||
|
if (mccCode >= '3000' && mccCode <= '3999') return 'Travel';
|
||||||
|
if (mccCode >= '4000' && mccCode <= '4799') return 'Transportation';
|
||||||
|
if (mccCode >= '7200' && mccCode <= '7999') return 'Entertainment';
|
||||||
|
if (mccCode >= '5900' && mccCode <= '5999') return 'Services';
|
||||||
|
if (mccCode >= '4800' && mccCode <= '4899') return 'Utilities';
|
||||||
|
if (mccCode >= '8000' && mccCode <= '8999') return 'Health & Wellness';
|
||||||
|
|
||||||
|
return 'Other';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
24
src/card/dtos/responses/transaction-item.response.dto.ts
Normal file
24
src/card/dtos/responses/transaction-item.response.dto.ts
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { ParentTransactionType } from '~/card/enums';
|
||||||
|
|
||||||
|
export class TransactionItemResponseDto {
|
||||||
|
@ApiProperty()
|
||||||
|
date!: Date;
|
||||||
|
|
||||||
|
@ApiProperty({ example: -50.0 })
|
||||||
|
amountSigned!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: ParentTransactionType })
|
||||||
|
type!: ParentTransactionType;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Counterparty display name (child for transfer, source label for top-up)' })
|
||||||
|
counterpartyName!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ nullable: true })
|
||||||
|
counterpartyAccountMasked!: string | null;
|
||||||
|
|
||||||
|
@ApiProperty({ required: false })
|
||||||
|
childName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -22,9 +22,30 @@ export class Account {
|
|||||||
@Column('varchar', { length: 255, nullable: false, name: 'currency' })
|
@Column('varchar', { length: 255, nullable: false, name: 'currency' })
|
||||||
currency!: string;
|
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;
|
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 })
|
@OneToMany(() => Card, (card) => card.account, { cascade: true })
|
||||||
cards!: Card[];
|
cards!: Card[];
|
||||||
|
|
||||||
|
|||||||
@ -32,7 +32,16 @@ export class Transaction {
|
|||||||
@Column({ name: 'rrn', nullable: true, type: 'varchar' })
|
@Column({ name: 'rrn', nullable: true, type: 'varchar' })
|
||||||
rrn!: string;
|
rrn!: string;
|
||||||
|
|
||||||
@Column({ type: 'decimal', precision: 12, scale: 2, name: 'transaction_amount' })
|
@Column({
|
||||||
|
type: 'decimal',
|
||||||
|
precision: 12,
|
||||||
|
scale: 2,
|
||||||
|
name: 'transaction_amount',
|
||||||
|
transformer: {
|
||||||
|
to: (value: number) => value,
|
||||||
|
from: (value: string) => parseFloat(value),
|
||||||
|
},
|
||||||
|
})
|
||||||
transactionAmount!: number;
|
transactionAmount!: number;
|
||||||
|
|
||||||
@Column({ type: 'varchar', name: 'transaction_currency' })
|
@Column({ type: 'varchar', name: 'transaction_currency' })
|
||||||
@ -50,6 +59,15 @@ export class Transaction {
|
|||||||
@Column({ type: 'decimal', name: 'vat_on_fees', precision: 12, scale: 2, default: 0.0 })
|
@Column({ type: 'decimal', name: 'vat_on_fees', precision: 12, scale: 2, default: 0.0 })
|
||||||
vatOnFees!: number;
|
vatOnFees!: number;
|
||||||
|
|
||||||
|
@Column({ name: 'merchant_name', type: 'varchar', nullable: true })
|
||||||
|
merchantName!: string | null;
|
||||||
|
|
||||||
|
@Column({ name: 'merchant_category_code', type: 'varchar', nullable: true })
|
||||||
|
merchantCategoryCode!: string | null;
|
||||||
|
|
||||||
|
@Column({ name: 'merchant_city', type: 'varchar', nullable: true })
|
||||||
|
merchantCity!: string | null;
|
||||||
|
|
||||||
@Column({ name: 'card_id', type: 'uuid', nullable: true })
|
@Column({ name: 'card_id', type: 'uuid', nullable: true })
|
||||||
cardId!: string;
|
cardId!: string;
|
||||||
|
|
||||||
|
|||||||
@ -6,3 +6,4 @@ export * from './card-status.enum';
|
|||||||
export * from './customer-type.enum';
|
export * from './customer-type.enum';
|
||||||
export * from './transaction-scope.enum';
|
export * from './transaction-scope.enum';
|
||||||
export * from './transaction-type.enum';
|
export * from './transaction-type.enum';
|
||||||
|
export * from './parent-transaction-type.enum';
|
||||||
|
|||||||
6
src/card/enums/parent-transaction-type.enum.ts
Normal file
6
src/card/enums/parent-transaction-type.enum.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export enum ParentTransactionType {
|
||||||
|
PARENT_TRANSFER = 'PARENT_TRANSFER',
|
||||||
|
PARENT_TOPUP = 'PARENT_TOPUP',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -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> {
|
getAccountByAccountNumber(accountNumber: string): Promise<Account | null> {
|
||||||
return this.accountRepository.findOne({
|
return this.accountRepository.findOne({
|
||||||
where: { accountNumber },
|
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) {
|
topUpAccountBalance(accountReference: string, amount: number) {
|
||||||
return this.accountRepository.increment({ accountReference }, 'balance', amount);
|
return this.accountRepository.increment({ accountReference }, 'balance', amount);
|
||||||
}
|
}
|
||||||
@ -41,4 +55,12 @@ export class AccountRepository {
|
|||||||
decreaseAccountBalance(accountReference: string, amount: number) {
|
decreaseAccountBalance(accountReference: string, amount: number) {
|
||||||
return this.accountRepository.decrement({ accountReference }, 'balance', amount);
|
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,
|
accountId: string,
|
||||||
card: CreateApplicationResponse,
|
card: CreateApplicationResponse,
|
||||||
cardColor?: CardColors,
|
cardColor?: CardColors,
|
||||||
|
parentId?: string,
|
||||||
): Promise<Card> {
|
): Promise<Card> {
|
||||||
return this.cardRepository.save(
|
return this.cardRepository.save(
|
||||||
this.cardRepository.create({
|
this.cardRepository.create({
|
||||||
customerId: customerId,
|
customerId: customerId,
|
||||||
expiry: card.expiryDate,
|
expiry: card.expiryDate,
|
||||||
cardReference: card.cardId,
|
cardReference: card.cardId,
|
||||||
customerType: CustomerType.PARENT,
|
customerType: parentId ? CustomerType.CHILD : CustomerType.PARENT,
|
||||||
firstSixDigits: card.firstSixDigits,
|
firstSixDigits: card.firstSixDigits,
|
||||||
lastFourDigits: card.lastFourDigits,
|
lastFourDigits: card.lastFourDigits,
|
||||||
color: cardColor ? cardColor : CardColors.DEEP_MAGENTA,
|
color: cardColor ? cardColor : CardColors.DEEP_MAGENTA,
|
||||||
@ -28,14 +29,29 @@ export class CardRepository {
|
|||||||
issuer: CardIssuers.NEOLEAP,
|
issuer: CardIssuers.NEOLEAP,
|
||||||
accountId: accountId,
|
accountId: accountId,
|
||||||
vpan: card.vpan,
|
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> {
|
getCardById(id: string): Promise<Card | null> {
|
||||||
return this.cardRepository.findOne({ where: { id }, relations: ['account'] });
|
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> {
|
getCardByReferenceNumber(referenceNumber: string): Promise<Card | null> {
|
||||||
return this.cardRepository.findOne({ where: { cardReference: referenceNumber }, relations: ['account'] });
|
return this.cardRepository.findOne({ where: { cardReference: referenceNumber }, relations: ['account'] });
|
||||||
}
|
}
|
||||||
@ -60,4 +76,10 @@ export class CardRepository {
|
|||||||
statusDescription: statusDescription,
|
statusDescription: statusDescription,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
updateCardLimit(cardId: string, newLimit: number) {
|
||||||
|
return this.cardRepository.update(cardId, {
|
||||||
|
limit: newLimit,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1 +1,3 @@
|
|||||||
export * from './card.repository';
|
export * from './card.repository';
|
||||||
|
export * from './transaction.repository';
|
||||||
|
export * from './account.repository';
|
||||||
|
|||||||
@ -34,6 +34,9 @@ export class TransactionRepository {
|
|||||||
accountReference: card.account!.accountReference,
|
accountReference: card.account!.accountReference,
|
||||||
transactionScope: TransactionScope.CARD,
|
transactionScope: TransactionScope.CARD,
|
||||||
vatOnFees: transactionData.vatOnFees,
|
vatOnFees: transactionData.vatOnFees,
|
||||||
|
merchantName: transactionData.cardAcceptorLocation?.merchantName || null,
|
||||||
|
merchantCategoryCode: transactionData.cardAcceptorLocation?.mcc || null,
|
||||||
|
merchantCity: transactionData.cardAcceptorLocation?.merchantCity || null,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -57,9 +60,124 @@ 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> {
|
findTransactionByReference(transactionId: string, accountReference: string): Promise<Transaction | null> {
|
||||||
return this.transactionRepository.findOne({
|
return this.transactionRepository.findOne({
|
||||||
where: { transactionId, accountReference },
|
where: { transactionId, accountReference },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getTransactionsForCardWithinDateRange(juniorId: string, startDate: Date, endDate: Date): Promise<Transaction[]> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('transaction')
|
||||||
|
.innerJoinAndSelect('transaction.card', 'card')
|
||||||
|
.where('card.customerId = :juniorId', { juniorId })
|
||||||
|
.andWhere('transaction.transactionScope = :scope', { scope: TransactionScope.CARD })
|
||||||
|
.andWhere('transaction.transactionType = :type', { type: TransactionType.EXTERNAL })
|
||||||
|
.andWhere('transaction.transactionDate BETWEEN :startDate AND :endDate', { startDate, endDate })
|
||||||
|
.orderBy('transaction.transactionDate', 'DESC')
|
||||||
|
.getMany();
|
||||||
|
}
|
||||||
|
|
||||||
|
findParentTransfers(guardianCustomerId: string, skip: number, take: number): Promise<Transaction[]> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('tx')
|
||||||
|
.innerJoinAndSelect('tx.card', 'card')
|
||||||
|
.innerJoinAndSelect('card.customer', 'childCustomer')
|
||||||
|
.innerJoinAndSelect('card.account', 'account')
|
||||||
|
.where('card.parentId = :guardianCustomerId', { guardianCustomerId })
|
||||||
|
.andWhere('tx.transactionScope = :scope', { scope: TransactionScope.CARD })
|
||||||
|
.andWhere('tx.transactionType = :type', { type: TransactionType.INTERNAL })
|
||||||
|
.orderBy('tx.transactionDate', 'DESC')
|
||||||
|
.skip(skip)
|
||||||
|
.take(take)
|
||||||
|
.getMany();
|
||||||
|
}
|
||||||
|
|
||||||
|
findParentTopups(guardianCustomerId: string, skip: number, take: number): Promise<Transaction[]> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('tx')
|
||||||
|
.innerJoinAndSelect('tx.account', 'account')
|
||||||
|
.leftJoinAndSelect('account.cards', 'parentCards')
|
||||||
|
.where('tx.transactionScope = :scope', { scope: TransactionScope.ACCOUNT })
|
||||||
|
.andWhere('parentCards.customerId = :guardianCustomerId', { guardianCustomerId })
|
||||||
|
.orderBy('tx.transactionDate', 'DESC')
|
||||||
|
.skip(skip)
|
||||||
|
.take(take)
|
||||||
|
.getMany();
|
||||||
|
}
|
||||||
|
|
||||||
|
countParentTransfers(guardianCustomerId: string): Promise<number> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('tx')
|
||||||
|
.innerJoin('tx.card', 'card')
|
||||||
|
.where('card.parentId = :guardianCustomerId', { guardianCustomerId })
|
||||||
|
.andWhere('tx.transactionScope = :scope', { scope: TransactionScope.CARD })
|
||||||
|
.andWhere('tx.transactionType = :type', { type: TransactionType.INTERNAL })
|
||||||
|
.getCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
countParentTopups(guardianCustomerId: string): Promise<number> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('tx')
|
||||||
|
.innerJoin('tx.account', 'account')
|
||||||
|
.leftJoin('account.cards', 'parentCards')
|
||||||
|
.where('tx.transactionScope = :scope', { scope: TransactionScope.ACCOUNT })
|
||||||
|
.andWhere('parentCards.customerId = :guardianCustomerId', { guardianCustomerId })
|
||||||
|
.getCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
findTransfersToJunior(juniorId: string, skip: number, take: number): Promise<Transaction[]> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('tx')
|
||||||
|
.innerJoinAndSelect('tx.card', 'card')
|
||||||
|
.innerJoinAndSelect('card.account', 'account')
|
||||||
|
.where('card.customerId = :juniorId', { juniorId })
|
||||||
|
.andWhere('tx.transactionScope = :scope', { scope: TransactionScope.CARD })
|
||||||
|
.andWhere('tx.transactionType = :type', { type: TransactionType.INTERNAL })
|
||||||
|
.orderBy('tx.transactionDate', 'DESC')
|
||||||
|
.skip(skip)
|
||||||
|
.take(take)
|
||||||
|
.getMany();
|
||||||
|
}
|
||||||
|
|
||||||
|
countTransfersToJunior(juniorId: string): Promise<number> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('tx')
|
||||||
|
.innerJoin('tx.card', 'card')
|
||||||
|
.where('card.customerId = :juniorId', { juniorId })
|
||||||
|
.andWhere('tx.transactionScope = :scope', { scope: TransactionScope.CARD })
|
||||||
|
.andWhere('tx.transactionType = :type', { type: TransactionType.INTERNAL })
|
||||||
|
.getCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
findTransactionById(transactionId: string, juniorId: string): Promise<Transaction | null> {
|
||||||
|
return this.transactionRepository
|
||||||
|
.createQueryBuilder('tx')
|
||||||
|
.innerJoinAndSelect('tx.card', 'card')
|
||||||
|
.where('tx.id = :transactionId', { transactionId })
|
||||||
|
.andWhere('card.customerId = :juniorId', { juniorId })
|
||||||
|
.getOne();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -27,15 +27,33 @@ export class AccountService {
|
|||||||
return account;
|
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);
|
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) {
|
async decreaseAccountBalance(accountReference: string, amount: number) {
|
||||||
const account = await this.getAccountByReferenceNumber(accountReference);
|
const account = await this.getAccountByReferenceNumber(accountReference);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
*
|
||||||
* While there is no need to check for insufficient balance because this is a webhook handler,
|
* 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) {
|
if (account.balance < amount) {
|
||||||
@ -44,4 +62,21 @@ export class AccountService {
|
|||||||
|
|
||||||
return this.accountRepository.decreaseAccountBalance(accountReference, amount);
|
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);
|
||||||
|
return this.accountRepository.topUpAccountBalance(account.accountReference, amount);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,21 +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 { Transactional } from 'typeorm-transactional';
|
||||||
import { AccountCardStatusChangedWebhookRequest } from '~/common/modules/neoleap/dtos/requests';
|
import { AccountCardStatusChangedWebhookRequest } from '~/common/modules/neoleap/dtos/requests';
|
||||||
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
||||||
import { Customer } from '~/customer/entities';
|
import { Customer } from '~/customer/entities';
|
||||||
import { KycStatus } from '~/customer/enums';
|
import { KycStatus } from '~/customer/enums';
|
||||||
import { CustomerService } from '~/customer/services';
|
import { CustomerService } from '~/customer/services';
|
||||||
|
import { OciService } from '~/document/services';
|
||||||
import { Card } from '../entities';
|
import { Card } from '../entities';
|
||||||
import { CardColors } from '../enums';
|
import { CardColors } from '../enums';
|
||||||
import { CardStatusMapper } from '../mappers/card-status.mapper';
|
import { CardStatusMapper } from '../mappers/card-status.mapper';
|
||||||
import { CardRepository } from '../repositories';
|
import { CardRepository } from '../repositories';
|
||||||
import { AccountService } from './account.service';
|
import { AccountService } from './account.service';
|
||||||
|
import { TransactionService } from './transaction.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CardService {
|
export class CardService {
|
||||||
|
private readonly logger = new Logger(CardService.name);
|
||||||
constructor(
|
constructor(
|
||||||
private readonly cardRepository: CardRepository,
|
private readonly cardRepository: CardRepository,
|
||||||
private readonly accountService: AccountService,
|
private readonly accountService: AccountService,
|
||||||
|
private readonly ociService: OciService,
|
||||||
|
@Inject(forwardRef(() => TransactionService)) private readonly transactionService: TransactionService,
|
||||||
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
||||||
@Inject(forwardRef(() => CustomerService)) private readonly customerService: CustomerService,
|
@Inject(forwardRef(() => CustomerService)) private readonly customerService: CustomerService,
|
||||||
) {}
|
) {}
|
||||||
@ -39,6 +45,12 @@ export class CardService {
|
|||||||
return this.getCardById(createdCard.id);
|
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) {
|
async createCardForChild(parentCustomer: Customer, childCustomer: Customer, cardColor: CardColors, cardPin: string) {
|
||||||
const data = await this.neoleapService.createChildCard(parentCustomer, childCustomer, cardPin);
|
const data = await this.neoleapService.createChildCard(parentCustomer, childCustomer, cardPin);
|
||||||
const createdCard = await this.cardRepository.createCard(
|
const createdCard = await this.cardRepository.createCard(
|
||||||
@ -46,10 +58,20 @@ export class CardService {
|
|||||||
parentCustomer.cards[0].account.id,
|
parentCustomer.cards[0].account.id,
|
||||||
data,
|
data,
|
||||||
cardColor,
|
cardColor,
|
||||||
|
parentCustomer.id,
|
||||||
);
|
);
|
||||||
|
|
||||||
return this.getCardById(createdCard.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> {
|
async getCardById(id: string): Promise<Card> {
|
||||||
const card = await this.cardRepository.getCardById(id);
|
const card = await this.cardRepository.getCardById(id);
|
||||||
|
|
||||||
@ -84,6 +106,7 @@ export class CardService {
|
|||||||
if (!card) {
|
if (!card) {
|
||||||
throw new BadRequestException('CARD.NOT_FOUND');
|
throw new BadRequestException('CARD.NOT_FOUND');
|
||||||
}
|
}
|
||||||
|
|
||||||
return card;
|
return card;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,4 +122,65 @@ export class CardService {
|
|||||||
|
|
||||||
return this.neoleapService.getEmbossingInformation(card);
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
getWeeklySummary(juniorId: string, startDate?: Date, endDate?: Date) {
|
||||||
|
return this.transactionService.getWeeklySummary(juniorId, startDate, endDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1 +1,3 @@
|
|||||||
export * from './card.service';
|
export * from './card.service';
|
||||||
|
export * from './transaction.service';
|
||||||
|
export * from './account.service';
|
||||||
|
|||||||
@ -1,21 +1,32 @@
|
|||||||
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
|
import { forwardRef, Inject, Injectable, UnprocessableEntityException } from '@nestjs/common';
|
||||||
import Decimal from 'decimal.js';
|
import Decimal from 'decimal.js';
|
||||||
|
import moment from 'moment';
|
||||||
import { Transactional } from 'typeorm-transactional';
|
import { Transactional } from 'typeorm-transactional';
|
||||||
import {
|
import {
|
||||||
AccountTransactionWebhookRequest,
|
AccountTransactionWebhookRequest,
|
||||||
CardTransactionWebhookRequest,
|
CardTransactionWebhookRequest,
|
||||||
} from '~/common/modules/neoleap/dtos/requests';
|
} from '~/common/modules/neoleap/dtos/requests';
|
||||||
import { Transaction } from '../entities/transaction.entity';
|
import { Transaction } from '../entities/transaction.entity';
|
||||||
|
import { CustomerType, TransactionType } from '../enums';
|
||||||
import { TransactionRepository } from '../repositories/transaction.repository';
|
import { TransactionRepository } from '../repositories/transaction.repository';
|
||||||
import { AccountService } from './account.service';
|
import { AccountService } from './account.service';
|
||||||
import { CardService } from './card.service';
|
import { CardService } from './card.service';
|
||||||
|
import {
|
||||||
|
TransactionItemResponseDto,
|
||||||
|
PagedTransactionsResponseDto,
|
||||||
|
ParentTransferItemDto,
|
||||||
|
PagedParentTransfersResponseDto,
|
||||||
|
ChildTransferItemDto,
|
||||||
|
PagedChildTransfersResponseDto,
|
||||||
|
} from '../dtos/responses';
|
||||||
|
import { ParentTransactionType } from '../enums';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TransactionService {
|
export class TransactionService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly transactionRepository: TransactionRepository,
|
private readonly transactionRepository: TransactionRepository,
|
||||||
private readonly accountService: AccountService,
|
private readonly accountService: AccountService,
|
||||||
private readonly cardService: CardService,
|
@Inject(forwardRef(() => CardService)) private readonly cardService: CardService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
@ -30,7 +41,14 @@ export class TransactionService {
|
|||||||
const transaction = await this.transactionRepository.createCardTransaction(card, body);
|
const transaction = await this.transactionRepository.createCardTransaction(card, body);
|
||||||
const total = new Decimal(body.transactionAmount).plus(body.billingAmount).plus(body.fees).plus(body.vatOnFees);
|
const total = new Decimal(body.transactionAmount).plus(body.billingAmount).plus(body.fees).plus(body.vatOnFees);
|
||||||
|
|
||||||
|
if (card.customerType === CustomerType.CHILD) {
|
||||||
|
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());
|
await this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber());
|
||||||
|
}
|
||||||
|
|
||||||
return transaction;
|
return transaction;
|
||||||
}
|
}
|
||||||
@ -51,6 +69,12 @@ export class TransactionService {
|
|||||||
return transaction;
|
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> {
|
private async findExistingTransaction(transactionId: string, accountReference: string): Promise<Transaction | null> {
|
||||||
const existingTransaction = await this.transactionRepository.findTransactionByReference(
|
const existingTransaction = await this.transactionRepository.findTransactionByReference(
|
||||||
transactionId,
|
transactionId,
|
||||||
@ -59,4 +83,233 @@ export class TransactionService {
|
|||||||
|
|
||||||
return existingTransaction;
|
return existingTransaction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getWeeklySummary(juniorId: string, startDate?: Date, endDate?: Date) {
|
||||||
|
let startOfWeek: Date;
|
||||||
|
let endOfWeek: Date;
|
||||||
|
|
||||||
|
if (startDate && endDate) {
|
||||||
|
startOfWeek = startDate;
|
||||||
|
endOfWeek = endDate;
|
||||||
|
} else {
|
||||||
|
const now = moment();
|
||||||
|
const dayOfWeek = now.day();
|
||||||
|
|
||||||
|
startOfWeek = moment().subtract(dayOfWeek, 'days').startOf('day').toDate();
|
||||||
|
|
||||||
|
endOfWeek = moment().add(6 - dayOfWeek, 'days').endOf('day').toDate();
|
||||||
|
}
|
||||||
|
|
||||||
|
const transactions = await this.transactionRepository.getTransactionsForCardWithinDateRange(
|
||||||
|
juniorId,
|
||||||
|
startOfWeek,
|
||||||
|
endOfWeek,
|
||||||
|
);
|
||||||
|
|
||||||
|
const summary = {
|
||||||
|
startOfWeek: startOfWeek,
|
||||||
|
endOfWeek: endOfWeek,
|
||||||
|
total: 0,
|
||||||
|
monday: 0,
|
||||||
|
tuesday: 0,
|
||||||
|
wednesday: 0,
|
||||||
|
thursday: 0,
|
||||||
|
friday: 0,
|
||||||
|
saturday: 0,
|
||||||
|
sunday: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
transactions.forEach((transaction) => {
|
||||||
|
const day = moment(transaction.transactionDate).format('dddd').toLowerCase() as
|
||||||
|
| 'monday'
|
||||||
|
| 'tuesday'
|
||||||
|
| 'wednesday'
|
||||||
|
| 'thursday'
|
||||||
|
| 'friday'
|
||||||
|
| 'saturday'
|
||||||
|
| 'sunday';
|
||||||
|
summary[day] += transaction.transactionAmount;
|
||||||
|
});
|
||||||
|
|
||||||
|
summary.total = transactions.reduce((acc, curr) => acc + curr.transactionAmount, 0);
|
||||||
|
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getParentConsolidated(
|
||||||
|
guardianCustomerId: string,
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
): Promise<TransactionItemResponseDto[]> {
|
||||||
|
const skip = (page - 1) * size;
|
||||||
|
|
||||||
|
const [transfers, topups] = await Promise.all([
|
||||||
|
this.transactionRepository.findParentTransfers(guardianCustomerId, skip, size),
|
||||||
|
this.transactionRepository.findParentTopups(guardianCustomerId, skip, size),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const merged = [...transfers, ...topups].sort(
|
||||||
|
(a, b) => new Date(b.transactionDate).getTime() - new Date(a.transactionDate).getTime(),
|
||||||
|
);
|
||||||
|
|
||||||
|
const trimmed = merged.slice(0, size);
|
||||||
|
|
||||||
|
return trimmed.map((t) => this.mapParentItem(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getParentTransactionsPaginated(
|
||||||
|
guardianCustomerId: string,
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
type?: ParentTransactionType,
|
||||||
|
): Promise<PagedTransactionsResponseDto> {
|
||||||
|
const skip = (page - 1) * size;
|
||||||
|
|
||||||
|
let transfers: Transaction[] = [];
|
||||||
|
let topups: Transaction[] = [];
|
||||||
|
let transferCount = 0;
|
||||||
|
let topupCount = 0;
|
||||||
|
|
||||||
|
if (!type || type === ParentTransactionType.PARENT_TRANSFER) {
|
||||||
|
[transfers, transferCount] = await Promise.all([
|
||||||
|
this.transactionRepository.findParentTransfers(guardianCustomerId, skip, size),
|
||||||
|
this.transactionRepository.countParentTransfers(guardianCustomerId),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!type || type === ParentTransactionType.PARENT_TOPUP) {
|
||||||
|
[topups, topupCount] = await Promise.all([
|
||||||
|
this.transactionRepository.findParentTopups(guardianCustomerId, skip, size),
|
||||||
|
this.transactionRepository.countParentTopups(guardianCustomerId),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = transferCount + topupCount;
|
||||||
|
|
||||||
|
if (type) {
|
||||||
|
const items = type === ParentTransactionType.PARENT_TRANSFER ? transfers : topups;
|
||||||
|
const mapped = items.map((t) => this.mapParentItem(t));
|
||||||
|
return new PagedTransactionsResponseDto(mapped, page, size, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
const merged = [...transfers, ...topups].sort(
|
||||||
|
(a, b) => new Date(b.transactionDate).getTime() - new Date(a.transactionDate).getTime(),
|
||||||
|
);
|
||||||
|
|
||||||
|
const paginated = merged.slice(0, size);
|
||||||
|
const mapped = paginated.map((t) => this.mapParentItem(t));
|
||||||
|
|
||||||
|
return new PagedTransactionsResponseDto(mapped, page, size, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getParentTransfersOnly(guardianCustomerId: string, page: number, size: number): Promise<ParentTransferItemDto[]> {
|
||||||
|
const skip = (page - 1) * size;
|
||||||
|
const transfers = await this.transactionRepository.findParentTransfers(guardianCustomerId, skip, size);
|
||||||
|
return transfers.map((t) => this.mapToParentTransferItem(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getParentTransfersPaginated(
|
||||||
|
guardianCustomerId: string,
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
): Promise<PagedParentTransfersResponseDto> {
|
||||||
|
const skip = (page - 1) * size;
|
||||||
|
const [transfers, total] = await Promise.all([
|
||||||
|
this.transactionRepository.findParentTransfers(guardianCustomerId, skip, size),
|
||||||
|
this.transactionRepository.countParentTransfers(guardianCustomerId),
|
||||||
|
]);
|
||||||
|
const items = transfers.map((t) => this.mapToParentTransferItem(t));
|
||||||
|
return new PagedParentTransfersResponseDto(items, page, size, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getChildTransfers(juniorId: string, page: number, size: number): Promise<ChildTransferItemDto[]> {
|
||||||
|
const skip = (page - 1) * size;
|
||||||
|
const transfers = await this.transactionRepository.findTransfersToJunior(juniorId, skip, size);
|
||||||
|
return transfers.map((t) => this.mapToChildTransferItem(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getChildTransfersPaginated(
|
||||||
|
juniorId: string,
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
): Promise<PagedChildTransfersResponseDto> {
|
||||||
|
const skip = (page - 1) * size;
|
||||||
|
const [transfers, total] = await Promise.all([
|
||||||
|
this.transactionRepository.findTransfersToJunior(juniorId, skip, size),
|
||||||
|
this.transactionRepository.countTransfersToJunior(juniorId),
|
||||||
|
]);
|
||||||
|
const items = transfers.map((t) => this.mapToChildTransferItem(t));
|
||||||
|
return new PagedChildTransfersResponseDto(items, page, size, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapToParentTransferItem(t: Transaction): ParentTransferItemDto {
|
||||||
|
const child = t.card?.customer;
|
||||||
|
const currency = t.transactionCurrency === '682' ? 'SAR' : t.transactionCurrency;
|
||||||
|
return {
|
||||||
|
date: t.transactionDate,
|
||||||
|
amount: Math.abs(t.transactionAmount),
|
||||||
|
currency,
|
||||||
|
childName: child ? `${child.firstName} ${child.lastName}` : 'Child',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapToChildTransferItem(t: Transaction): ChildTransferItemDto {
|
||||||
|
const amount = Math.abs(t.transactionAmount);
|
||||||
|
const currency = t.transactionCurrency === '682' ? 'SAR' : t.transactionCurrency;
|
||||||
|
return {
|
||||||
|
date: t.transactionDate,
|
||||||
|
amount,
|
||||||
|
currency,
|
||||||
|
message: `You received {{amount}} {{currency}} from your parent.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getChildSpendingHistory(juniorId: string, startUtc: Date, endUtc: Date) {
|
||||||
|
const transactions = await this.transactionRepository.getTransactionsForCardWithinDateRange(
|
||||||
|
juniorId,
|
||||||
|
startUtc,
|
||||||
|
endUtc,
|
||||||
|
);
|
||||||
|
|
||||||
|
const { SpendingHistoryItemDto, SpendingHistoryResponseDto } = await import('../dtos/responses');
|
||||||
|
const items = transactions.map((t) => new SpendingHistoryItemDto(t));
|
||||||
|
return new SpendingHistoryResponseDto(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTransactionDetail(transactionId: string, juniorId: string) {
|
||||||
|
const transaction = await this.transactionRepository.findTransactionById(transactionId, juniorId);
|
||||||
|
|
||||||
|
if (!transaction) {
|
||||||
|
throw new UnprocessableEntityException('TRANSACTION.NOT_FOUND');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { TransactionDetailResponseDto } = await import('../dtos/responses');
|
||||||
|
return new TransactionDetailResponseDto(transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapParentItem(t: Transaction): TransactionItemResponseDto {
|
||||||
|
const dto = new TransactionItemResponseDto();
|
||||||
|
dto.date = t.transactionDate;
|
||||||
|
|
||||||
|
if (t.transactionType === TransactionType.INTERNAL) {
|
||||||
|
dto.type = ParentTransactionType.PARENT_TRANSFER;
|
||||||
|
dto.amountSigned = -Math.abs(t.transactionAmount);
|
||||||
|
const child = t.card?.customer;
|
||||||
|
dto.counterpartyName = child ? `${child.firstName} ${child.lastName}` : 'Child';
|
||||||
|
dto.childName = dto.counterpartyName;
|
||||||
|
dto.counterpartyAccountMasked = t.card?.account?.accountReference
|
||||||
|
? `****${t.card.account.accountReference.slice(-4)}`
|
||||||
|
: null;
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
dto.type = ParentTransactionType.PARENT_TOPUP;
|
||||||
|
const settlement = Number(t.settlementAmount ?? 0);
|
||||||
|
const txn = Number(t.transactionAmount ?? 0);
|
||||||
|
const creditAmount = settlement > 0 ? settlement : txn;
|
||||||
|
dto.amountSigned = Math.abs(Number.isFinite(creditAmount) ? creditAmount : 0);
|
||||||
|
dto.counterpartyName = 'Top-up';
|
||||||
|
dto.counterpartyAccountMasked = t.accountReference ? `****${t.accountReference.slice(-4)}` : null;
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,19 +1,25 @@
|
|||||||
function getRandomWithDigits(digits: number): string {
|
import { randomInt, randomUUID } from 'crypto';
|
||||||
const min = Math.pow(10, digits - 1); // e.g. 1000 for 4 digits
|
|
||||||
const max = Math.pow(10, digits) - 1; // e.g. 9999 for 4 digits
|
|
||||||
|
|
||||||
const result = Math.floor(Math.random() * (max - min + 1)) + min;
|
/** Generate a string of `n` random digits (first digit never 0). */
|
||||||
return result.toString();
|
function randomDigits(n: number): string {
|
||||||
|
if (n <= 0) return '0';
|
||||||
|
let s = String(randomInt(1, 10)); // first digit 1–9
|
||||||
|
for (let i = 1; i < n; i++) s += String(randomInt(0, 10));
|
||||||
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CREATE_APPLICATION_MOCK = {
|
/** Build a fresh mock object every time it's called */
|
||||||
|
export function buildCreateApplicationMock() {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
return {
|
||||||
ResponseHeader: {
|
ResponseHeader: {
|
||||||
Version: '1.0.0',
|
Version: '1.0.0',
|
||||||
MsgUid: 'adaa1893-9f95-48a8-b7a1-0422bcf629b5',
|
MsgUid: randomUUID(),
|
||||||
Source: 'ZOD',
|
Source: 'ZOD',
|
||||||
ServiceId: 'CreateNewApplication',
|
ServiceId: 'CreateNewApplication',
|
||||||
ReqDateTime: '2025-06-03T07:32:16.304Z',
|
ReqDateTime: now,
|
||||||
RspDateTime: '2025-06-03T08:21:15.662',
|
RspDateTime: now,
|
||||||
ResponseCode: '000',
|
ResponseCode: '000',
|
||||||
ResponseType: 'Success',
|
ResponseType: 'Success',
|
||||||
ProcessingTime: 1665,
|
ProcessingTime: 1665,
|
||||||
@ -81,26 +87,11 @@ export const CREATE_APPLICATION_MOCK = {
|
|||||||
EmployerName: 'N/A',
|
EmployerName: 'N/A',
|
||||||
EmploymentYears: 0,
|
EmploymentYears: 0,
|
||||||
EmploymentMonths: 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,
|
CIF: null,
|
||||||
BankAccountNumber: ' ',
|
BankAccountNumber: ' ',
|
||||||
Currency: {
|
Currency: { CurrCode: '682', AlphaCode: 'SAR' },
|
||||||
CurrCode: '682',
|
|
||||||
AlphaCode: 'SAR',
|
|
||||||
},
|
|
||||||
RequestedCurrencyList: null,
|
|
||||||
CreditAccountNumber: '6000000000000000',
|
CreditAccountNumber: '6000000000000000',
|
||||||
AccountType: '30',
|
AccountType: '30',
|
||||||
OpenDate: null,
|
|
||||||
Income: 0,
|
Income: 0,
|
||||||
AdditionalIncome: 0,
|
AdditionalIncome: 0,
|
||||||
TotalIncome: 0,
|
TotalIncome: 0,
|
||||||
@ -115,551 +106,28 @@ export const CREATE_APPLICATION_MOCK = {
|
|||||||
AutoDebit: 'N',
|
AutoDebit: 'N',
|
||||||
PaymentMethod: '2',
|
PaymentMethod: '2',
|
||||||
BillingCycle: 'C1',
|
BillingCycle: 'C1',
|
||||||
OldIssueDate: null,
|
|
||||||
OtherPaymentsDate: null,
|
|
||||||
MaximumDelinquency: null,
|
MaximumDelinquency: null,
|
||||||
CreditBureauDecision: null,
|
CreditBureauDecision: null,
|
||||||
CreditBureauUserData: null,
|
|
||||||
ECommerce: 'N',
|
ECommerce: 'N',
|
||||||
NumberOfCards: 0,
|
NumberOfCards: 0,
|
||||||
OtherBank: null,
|
|
||||||
OtherBankDescription: null,
|
|
||||||
InsuranceProduct: null,
|
|
||||||
SocialCode: '000',
|
SocialCode: '000',
|
||||||
JobGrade: 0,
|
JobGrade: 0,
|
||||||
Flags: [
|
Flags: Array.from({ length: 64 }, (_, i) => ({
|
||||||
{
|
Position: i + 1,
|
||||||
Position: 1,
|
|
||||||
Value: '0',
|
Value: '0',
|
||||||
},
|
})),
|
||||||
{
|
CheckFlags: Array.from({ length: 64 }, (_, i) => ({
|
||||||
Position: 2,
|
Position: i + 1,
|
||||||
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,
|
|
||||||
Value: '0',
|
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: {
|
ApplicationStatusDetails: {
|
||||||
StatusCode: '04',
|
StatusCode: '04',
|
||||||
Description: 'Approved',
|
Description: 'Approved',
|
||||||
Canceled: false,
|
Canceled: false,
|
||||||
},
|
},
|
||||||
CorporateDetails: null,
|
|
||||||
CustomerDetails: {
|
CustomerDetails: {
|
||||||
Id: 115158,
|
Id: 115158,
|
||||||
CustomerCode: '100000024619',
|
CustomerCode: '100000024619',
|
||||||
@ -668,8 +136,8 @@ export const CREATE_APPLICATION_MOCK = {
|
|||||||
PreferredLanguage: 'EN',
|
PreferredLanguage: 'EN',
|
||||||
ExternalCustomerCode: null,
|
ExternalCustomerCode: null,
|
||||||
Title: ' ',
|
Title: ' ',
|
||||||
FirstName: ' ',
|
FirstName: ' ',
|
||||||
LastName: ' ',
|
LastName: ' ',
|
||||||
DateOfBirth: null,
|
DateOfBirth: null,
|
||||||
UserData1: '2031-09-17',
|
UserData1: '2031-09-17',
|
||||||
UserData2: '01',
|
UserData2: '01',
|
||||||
@ -679,75 +147,46 @@ export const CREATE_APPLICATION_MOCK = {
|
|||||||
Gender: 'U',
|
Gender: 'U',
|
||||||
Married: 'U',
|
Married: 'U',
|
||||||
},
|
},
|
||||||
|
|
||||||
AccountDetailsList: [
|
AccountDetailsList: [
|
||||||
{
|
{
|
||||||
Id: getRandomWithDigits(5),
|
Id: randomDigits(5),
|
||||||
InstitutionCode: '1100',
|
InstitutionCode: '1100',
|
||||||
AccountNumber: getRandomWithDigits(16),
|
AccountNumber: randomDigits(16),
|
||||||
Currency: {
|
Currency: { CurrCode: '682', AlphaCode: 'SAR' },
|
||||||
CurrCode: '682',
|
|
||||||
AlphaCode: 'SAR',
|
|
||||||
},
|
|
||||||
AccountTypeCode: '30',
|
AccountTypeCode: '30',
|
||||||
ClassId: '2',
|
ClassId: '2',
|
||||||
AccountStatus: '00',
|
AccountStatus: '00',
|
||||||
VipFlag: '0',
|
VipFlag: '0',
|
||||||
BlockedAmount: 0,
|
BlockedAmount: 0,
|
||||||
EquivalentBlockedAmount: null,
|
|
||||||
UnclearCredit: 0,
|
|
||||||
EquivalentUnclearCredit: null,
|
|
||||||
AvailableBalance: 0,
|
AvailableBalance: 0,
|
||||||
EquivalentAvailableBalance: null,
|
|
||||||
AvailableBalanceToSpend: 0,
|
|
||||||
CreditLimit: 0,
|
|
||||||
RemainingCashLimit: null,
|
|
||||||
UserData1: 'D36407C9AE4C28D2185',
|
UserData1: 'D36407C9AE4C28D2185',
|
||||||
UserData2: null,
|
|
||||||
UserData3: 'D36407C9AE4C28D2185',
|
UserData3: 'D36407C9AE4C28D2185',
|
||||||
UserData4: null,
|
UserData5: `SA${randomDigits(22)}`,
|
||||||
UserData5: 'SA2380900000752991120011',
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|
||||||
CardDetailsList: [
|
CardDetailsList: [
|
||||||
{
|
{
|
||||||
pvv: null,
|
pvv: null,
|
||||||
ResponseCardIdentifier: {
|
ResponseCardIdentifier: {
|
||||||
Id: getRandomWithDigits(5),
|
Id: randomDigits(5),
|
||||||
Pan: 'DDDDDDDDDDDDDDDDDDD',
|
Pan: 'DDDDDDDDDDDDDDDDDDD',
|
||||||
MaskedPan: '999999_9999',
|
MaskedPan: '999999_9999',
|
||||||
VPan: getRandomWithDigits(16),
|
VPan: randomDigits(16),
|
||||||
Seqno: 0,
|
Seqno: 0,
|
||||||
},
|
},
|
||||||
ExpiryDate: '2031-09-30',
|
ExpiryDate: '2031-09-30',
|
||||||
EffectiveDate: '2025-06-02',
|
EffectiveDate: '2025-06-02',
|
||||||
CardStatus: '30',
|
CardStatus: '30',
|
||||||
OldPlasticExpiryDate: null,
|
|
||||||
OldPlasticCardStatus: null,
|
|
||||||
EmbossingName: 'ABDALHAMID AHMAD',
|
EmbossingName: 'ABDALHAMID AHMAD',
|
||||||
Title: 'Mr.',
|
Title: 'Mr.',
|
||||||
FirstName: 'Abdalhamid',
|
FirstName: 'Abdalhamid',
|
||||||
LastName: ' Ahmad',
|
LastName: ' Ahmad',
|
||||||
Additional: false,
|
|
||||||
BatchNumber: 8849,
|
BatchNumber: 8849,
|
||||||
ServiceCode: '226',
|
ServiceCode: '226',
|
||||||
Kinship: null,
|
|
||||||
DateOfBirth: '1999-01-07',
|
DateOfBirth: '1999-01-07',
|
||||||
LastActivity: null,
|
|
||||||
LastStatusChangeDate: '2025-06-03',
|
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',
|
PinStatus: '40',
|
||||||
OldPinStatus: '0',
|
OldPinStatus: '0',
|
||||||
CustomerIdNumber: '1089055972',
|
CustomerIdNumber: '1089055972',
|
||||||
@ -755,4 +194,5 @@ export const CREATE_APPLICATION_MOCK = {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|||||||
@ -56,12 +56,12 @@ export class AccountTransactionWebhookRequest {
|
|||||||
@ApiProperty({ example: '682' })
|
@ApiProperty({ example: '682' })
|
||||||
currency!: string;
|
currency!: string;
|
||||||
|
|
||||||
@Expose()
|
@Expose({ name: 'Date' })
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiProperty({ name: 'Date', example: '20241112' })
|
@ApiProperty({ name: 'Date', example: '20241112' })
|
||||||
date!: string;
|
date!: string;
|
||||||
|
|
||||||
@Expose()
|
@Expose({ name: 'Time' })
|
||||||
@IsString()
|
@IsString()
|
||||||
@ApiProperty({ name: 'Time', example: '125340' })
|
@ApiProperty({ name: 'Time', example: '125340' })
|
||||||
time!: string;
|
time!: string;
|
||||||
|
|||||||
@ -10,8 +10,8 @@ import { InitiateKycRequestDto } from '~/customer/dtos/request';
|
|||||||
import { Customer } from '~/customer/entities';
|
import { Customer } from '~/customer/entities';
|
||||||
import { Gender } from '~/customer/enums';
|
import { Gender } from '~/customer/enums';
|
||||||
import {
|
import {
|
||||||
|
buildCreateApplicationMock,
|
||||||
CARD_EMBOSSING_DETAILS_MOCK,
|
CARD_EMBOSSING_DETAILS_MOCK,
|
||||||
CREATE_APPLICATION_MOCK,
|
|
||||||
INITIATE_KYC_MOCK,
|
INITIATE_KYC_MOCK,
|
||||||
INQUIRE_APPLICATION_MOCK,
|
INQUIRE_APPLICATION_MOCK,
|
||||||
} from '../__mocks__/';
|
} from '../__mocks__/';
|
||||||
@ -95,7 +95,7 @@ export class NeoLeapService {
|
|||||||
const responseKey = 'CreateNewApplicationResponseDetails';
|
const responseKey = 'CreateNewApplicationResponseDetails';
|
||||||
|
|
||||||
if (!this.useGateway) {
|
if (!this.useGateway) {
|
||||||
return plainToInstance(CreateApplicationResponse, CREATE_APPLICATION_MOCK[responseKey], {
|
return plainToInstance(CreateApplicationResponse, buildCreateApplicationMock()[responseKey], {
|
||||||
excludeExtraneousValues: true,
|
excludeExtraneousValues: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -169,7 +169,7 @@ export class NeoLeapService {
|
|||||||
const responseKey = 'CreateNewApplicationResponseDetails';
|
const responseKey = 'CreateNewApplicationResponseDetails';
|
||||||
|
|
||||||
if (!this.useGateway) {
|
if (!this.useGateway) {
|
||||||
return plainToInstance(CreateApplicationResponse, CREATE_APPLICATION_MOCK[responseKey], {
|
return plainToInstance(CreateApplicationResponse, buildCreateApplicationMock()[responseKey], {
|
||||||
excludeExtraneousValues: true,
|
excludeExtraneousValues: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
export * from './response.factory.util';
|
|
||||||
export * from './i18n-context-wrapper.util';
|
|
||||||
export * from './class-validator-formatter.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 { Guardian } from '~/guardian/entities/guradian.entity';
|
||||||
import { Junior } from '~/junior/entities';
|
import { Junior } from '~/junior/entities';
|
||||||
import { User } from '~/user/entities';
|
import { User } from '~/user/entities';
|
||||||
import { CustomerStatus, KycStatus } from '../enums';
|
import { CustomerStatus, Gender, KycStatus } from '../enums';
|
||||||
|
|
||||||
@Entity('customers')
|
@Entity('customers')
|
||||||
export class Customer extends BaseEntity {
|
export class Customer extends BaseEntity {
|
||||||
@ -62,7 +62,7 @@ export class Customer extends BaseEntity {
|
|||||||
isPep!: boolean;
|
isPep!: boolean;
|
||||||
|
|
||||||
@Column('varchar', { length: 255, nullable: true, name: 'gender' })
|
@Column('varchar', { length: 255, nullable: true, name: 'gender' })
|
||||||
gender!: string;
|
gender!: Gender;
|
||||||
|
|
||||||
@Column('boolean', { default: false, name: 'is_junior' })
|
@Column('boolean', { default: false, name: 'is_junior' })
|
||||||
isJunior!: boolean;
|
isJunior!: boolean;
|
||||||
|
|||||||
@ -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"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,18 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class AddMerchantInfoToTransactions1760869651296 implements MigrationInterface {
|
||||||
|
name = 'AddMerchantInfoToTransactions1760869651296'
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "transactions" ADD COLUMN IF NOT EXISTS "merchant_name" character varying`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "transactions" ADD COLUMN IF NOT EXISTS "merchant_category_code" character varying`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "transactions" ADD COLUMN IF NOT EXISTS "merchant_city" character varying`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "transactions" DROP COLUMN "merchant_city"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "transactions" DROP COLUMN "merchant_category_code"`);
|
||||||
|
await queryRunner.query(`ALTER TABLE "transactions" DROP COLUMN "merchant_name"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class AddUniqueConstraintToUserEmail1761032305682 implements MigrationInterface {
|
||||||
|
name = 'AddUniqueConstraintToUserEmail1761032305682'
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
|
||||||
|
await queryRunner.query(`ALTER TABLE "users" ADD CONSTRAINT "UQ_97672ac88f789774dd47f7c8be3" UNIQUE ("email")`);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`ALTER TABLE "users" DROP CONSTRAINT "UQ_97672ac88f789774dd47f7c8be3"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -1,3 +1,8 @@
|
|||||||
export * from './1754913378460-initial-migration';
|
export * from './1754913378460-initial-migration';
|
||||||
export * from './1754915164809-create-neoleap-related-entities';
|
export * from './1754915164809-create-neoleap-related-entities';
|
||||||
export * from './1754915164810-seed-default-avatar';
|
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';
|
||||||
|
export * from './1760869651296-AddMerchantInfoToTransactions';
|
||||||
|
export * from './1761032305682-AddUniqueConstraintToUserEmail';
|
||||||
50
src/guardian/controllers/guardian-transactions.controller.ts
Normal file
50
src/guardian/controllers/guardian-transactions.controller.ts
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags, ApiQuery } 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, ApiLangRequestHeader } from '~/core/decorators';
|
||||||
|
import { ResponseFactory } from '~/core/utils';
|
||||||
|
import { ParentHomeResponseDto, PagedParentTransfersResponseDto } from '~/card/dtos/responses';
|
||||||
|
import { GuardianTransactionsService } from '../services';
|
||||||
|
|
||||||
|
|
||||||
|
@Controller('guardians/me')
|
||||||
|
@ApiTags('Guardians')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@ApiLangRequestHeader()
|
||||||
|
@UseGuards(AccessTokenGuard, RolesGuard)
|
||||||
|
@AllowedRoles(Roles.GUARDIAN)
|
||||||
|
export class GuardianTransactionsController {
|
||||||
|
constructor(private readonly guardianTxService: GuardianTransactionsService) {}
|
||||||
|
|
||||||
|
@Get('home')
|
||||||
|
@ApiQuery({ name: 'size', required: false, type: Number, example: 5 })
|
||||||
|
@ApiDataResponse(ParentHomeResponseDto)
|
||||||
|
async getHome(
|
||||||
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
|
@Query('size') size?: number,
|
||||||
|
) {
|
||||||
|
const limit = Math.max(1, Math.min(Number(size) || 5, 20));
|
||||||
|
const res = await this.guardianTxService.getHome(user.sub, limit);
|
||||||
|
return ResponseFactory.data(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('transfers')
|
||||||
|
@ApiQuery({ name: 'page', required: false, type: Number, example: 1 })
|
||||||
|
@ApiQuery({ name: 'size', required: false, type: Number, example: 10 })
|
||||||
|
@ApiDataResponse(PagedParentTransfersResponseDto)
|
||||||
|
async getTransfers(
|
||||||
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
|
@Query('page') page?: number,
|
||||||
|
@Query('size') size?: number,
|
||||||
|
) {
|
||||||
|
const pageNum = Math.max(1, Number(page) || 1);
|
||||||
|
const pageSize = Math.max(1, Math.min(Number(size) || 10, 50));
|
||||||
|
const res = await this.guardianTxService.getTransfers(user.sub, pageNum, pageSize);
|
||||||
|
return ResponseFactory.data(res);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
3
src/guardian/controllers/index.ts
Normal file
3
src/guardian/controllers/index.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export * from './guardian-transactions.controller';
|
||||||
|
|
||||||
|
|
||||||
@ -11,6 +11,7 @@ import {
|
|||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
import { Customer } from '~/customer/entities';
|
import { Customer } from '~/customer/entities';
|
||||||
import { Junior } from '~/junior/entities';
|
import { Junior } from '~/junior/entities';
|
||||||
|
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
|
||||||
|
|
||||||
@Entity('guardians')
|
@Entity('guardians')
|
||||||
export class Guardian extends BaseEntity {
|
export class Guardian extends BaseEntity {
|
||||||
@ -27,6 +28,9 @@ export class Guardian extends BaseEntity {
|
|||||||
@OneToMany(() => Junior, (junior) => junior.guardian)
|
@OneToMany(() => Junior, (junior) => junior.guardian)
|
||||||
juniors!: Junior[];
|
juniors!: Junior[];
|
||||||
|
|
||||||
|
@OneToMany(() => MoneyRequest, (moneyRequest) => moneyRequest.guardian)
|
||||||
|
moneyRequests!: MoneyRequest[];
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
createdAt!: Date;
|
createdAt!: Date;
|
||||||
|
|
||||||
|
|||||||
@ -1,12 +1,18 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { forwardRef } from '@nestjs/common';
|
||||||
|
import { CustomerModule } from '~/customer/customer.module';
|
||||||
|
import { CardModule } from '~/card/card.module';
|
||||||
|
import { GuardianTransactionsController } from './controllers/guardian-transactions.controller';
|
||||||
|
import { GuardianTransactionsService } from './services/guardian-transactions.service';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { Guardian } from './entities/guradian.entity';
|
import { Guardian } from './entities/guradian.entity';
|
||||||
import { GuardianRepository } from './repositories';
|
import { GuardianRepository } from './repositories';
|
||||||
import { GuardianService } from './services';
|
import { GuardianService } from './services';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
providers: [GuardianService, GuardianRepository],
|
providers: [GuardianService, GuardianRepository, GuardianTransactionsService],
|
||||||
imports: [TypeOrmModule.forFeature([Guardian])],
|
controllers: [GuardianTransactionsController],
|
||||||
|
imports: [TypeOrmModule.forFeature([Guardian]), forwardRef(() => CustomerModule), forwardRef(() => CardModule)],
|
||||||
exports: [GuardianService],
|
exports: [GuardianService],
|
||||||
})
|
})
|
||||||
export class GuardianModule {}
|
export class GuardianModule {}
|
||||||
|
|||||||
42
src/guardian/services/guardian-transactions.service.ts
Normal file
42
src/guardian/services/guardian-transactions.service.ts
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { CustomerService } from '~/customer/services';
|
||||||
|
import { ParentHomeResponseDto, PagedParentTransfersResponseDto } from '~/card/dtos/responses';
|
||||||
|
import { TransactionService } from '~/card/services/transaction.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class GuardianTransactionsService {
|
||||||
|
constructor(
|
||||||
|
private readonly customerService: CustomerService,
|
||||||
|
private readonly transactionService: TransactionService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async getHome(guardianId: string, size: number): Promise<ParentHomeResponseDto> {
|
||||||
|
const parent = await this.customerService.findCustomerById(guardianId);
|
||||||
|
const primaryCard = parent.cards?.[0];
|
||||||
|
|
||||||
|
let availableBalance = 0;
|
||||||
|
if (primaryCard) {
|
||||||
|
const hasLimit = typeof primaryCard.limit === 'number' && !Number.isNaN(primaryCard.limit);
|
||||||
|
const hasBalance = primaryCard.account && typeof primaryCard.account.balance === 'number';
|
||||||
|
if (hasLimit && hasBalance && primaryCard.limit > 0) {
|
||||||
|
availableBalance = Math.min(primaryCard.limit, primaryCard.account.balance);
|
||||||
|
} else if (hasBalance) {
|
||||||
|
availableBalance = primaryCard.account.balance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const recentTransfers = await this.transactionService.getParentTransfersOnly(guardianId, 1, size);
|
||||||
|
|
||||||
|
return new ParentHomeResponseDto(availableBalance, recentTransfers);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTransfers(
|
||||||
|
guardianId: string,
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
): Promise<PagedParentTransfersResponseDto> {
|
||||||
|
return this.transactionService.getParentTransfersPaginated(guardianId, page, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -1 +1,2 @@
|
|||||||
export * from './guardian.service';
|
export * from './guardian.service'
|
||||||
|
export * from './guardian-transactions.service'
|
||||||
|
|||||||
@ -67,16 +67,15 @@
|
|||||||
"NOT_FOUND": "لم يتم العثور على الطفل.",
|
"NOT_FOUND": "لم يتم العثور على الطفل.",
|
||||||
"CIVIL_ID_REQUIRED": "مطلوب بطاقة الهوية المدنية.",
|
"CIVIL_ID_REQUIRED": "مطلوب بطاقة الهوية المدنية.",
|
||||||
"CIVIL_ID_NOT_CREATED_BY_GUARDIAN": "تم تحميل بطاقة الهوية المدنية من قبل شخص آخر غير ولي الأمر.",
|
"CIVIL_ID_NOT_CREATED_BY_GUARDIAN": "تم تحميل بطاقة الهوية المدنية من قبل شخص آخر غير ولي الأمر.",
|
||||||
"CIVIL_ID_ALREADY_EXISTS": "بطاقة الهوية المدنية مستخدمة بالفعل من قبل طفل آخر."
|
"CIVIL_ID_ALREADY_EXISTS": "بطاقة الهوية المدنية مستخدمة بالفعل من قبل طفل آخر.",
|
||||||
|
"CANNOT_UPDATE_REGISTERED_USER": "الطفل قد سجل بالفعل. لا يُسمح بتحديث البيانات.",
|
||||||
|
"CANNOT_DELETE_REGISTERED_USER": "الطفل قد سجل بالفعل. لا يُسمح بحذف الطفل."
|
||||||
},
|
},
|
||||||
|
|
||||||
"MONEY_REQUEST": {
|
"MONEY_REQUEST": {
|
||||||
"START_DATE_IN_THE_PAST": "لا يمكن أن يكون تاريخ البدء في الماضي.",
|
|
||||||
"END_DATE_IN_THE_PAST": "لا يمكن أن يكون تاريخ النهاية في الماضي.",
|
|
||||||
"END_DATE_BEFORE_START_DATE": "لا يمكن أن يكون تاريخ النهاية قبل تاريخ البدء.",
|
|
||||||
"NOT_FOUND": "لم يتم العثور على طلب المال.",
|
"NOT_FOUND": "لم يتم العثور على طلب المال.",
|
||||||
"ENDED": "تم انتهاء طلب المال.",
|
"ALREADY_APPROVED": "تمت الموافقة على طلب المال بالفعل.",
|
||||||
"ALREADY_REVIEWED": "تمت مراجعة طلب المال بالفعل."
|
"ALREADY_REJECTED": "تم رفض طلب المال بالفعل."
|
||||||
},
|
},
|
||||||
|
|
||||||
"GOAL": {
|
"GOAL": {
|
||||||
@ -102,5 +101,10 @@
|
|||||||
},
|
},
|
||||||
"OTP": {
|
"OTP": {
|
||||||
"INVALID_OTP": "رمز التحقق الذي أدخلته غير صالح. يرجى المحاولة مرة أخرى."
|
"INVALID_OTP": "رمز التحقق الذي أدخلته غير صالح. يرجى المحاولة مرة أخرى."
|
||||||
|
},
|
||||||
|
"CARD": {
|
||||||
|
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
|
||||||
|
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر.",
|
||||||
|
"NOT_FOUND": "لم يتم العثور على البطاقة."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -66,16 +66,15 @@
|
|||||||
"NOT_FOUND": "The junior was not found.",
|
"NOT_FOUND": "The junior was not found.",
|
||||||
"CIVIL_ID_REQUIRED": "Civil ID is required.",
|
"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_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.",
|
||||||
|
"CANNOT_DELETE_REGISTERED_USER": "The junior has already registered. Deleting the junior is not allowed."
|
||||||
},
|
},
|
||||||
|
|
||||||
"MONEY_REQUEST": {
|
"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.",
|
"NOT_FOUND": "The money request was not found.",
|
||||||
"ENDED": "The money request has ended.",
|
"ALREADY_APPROVED": "The money request has already been approved.",
|
||||||
"ALREADY_REVIEWED": "The money request has already been reviewed."
|
"ALREADY_REJECTED": "The money request has already been rejected."
|
||||||
},
|
},
|
||||||
|
|
||||||
"GOAL": {
|
"GOAL": {
|
||||||
@ -101,5 +100,10 @@
|
|||||||
},
|
},
|
||||||
"OTP": {
|
"OTP": {
|
||||||
"INVALID_OTP": "The OTP you entered is invalid. Please try again."
|
"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.",
|
||||||
|
"NOT_FOUND": "The card was not found."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,17 @@
|
|||||||
import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
|
import {
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags, ApiQuery } from '@nestjs/swagger';
|
||||||
import { Roles } from '~/auth/enums';
|
import { Roles } from '~/auth/enums';
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
import { IJwtPayload } from '~/auth/interfaces';
|
||||||
import { AllowedRoles, AuthenticatedUser, Public } from '~/common/decorators';
|
import { AllowedRoles, AuthenticatedUser, Public } from '~/common/decorators';
|
||||||
@ -8,8 +20,20 @@ import { ApiDataPageResponse, ApiDataResponse, ApiLangRequestHeader } from '~/co
|
|||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
import { PageOptionsRequestDto } from '~/core/dtos';
|
||||||
import { CustomParseUUIDPipe } from '~/core/pipes';
|
import { CustomParseUUIDPipe } from '~/core/pipes';
|
||||||
import { ResponseFactory } from '~/core/utils';
|
import { ResponseFactory } from '~/core/utils';
|
||||||
import { CreateJuniorRequestDto, SetThemeRequestDto } from '../dtos/request';
|
import {
|
||||||
import { JuniorResponseDto, QrCodeValidationResponseDto, ThemeResponseDto } from '../dtos/response';
|
CreateJuniorRequestDto,
|
||||||
|
SetThemeRequestDto,
|
||||||
|
TransferToJuniorRequestDto,
|
||||||
|
UpdateJuniorRequestDto,
|
||||||
|
} from '../dtos/request';
|
||||||
|
import {
|
||||||
|
JuniorResponseDto,
|
||||||
|
QrCodeValidationResponseDto,
|
||||||
|
ThemeResponseDto,
|
||||||
|
TransferToJuniorResponseDto,
|
||||||
|
} from '../dtos/response';
|
||||||
|
import { WeeklySummaryResponseDto } from '../dtos/response/weekly-summary.response.dto';
|
||||||
|
import { JuniorHomeResponseDto, PagedChildTransfersResponseDto } from '~/card/dtos/responses';
|
||||||
import { JuniorService } from '../services';
|
import { JuniorService } from '../services';
|
||||||
|
|
||||||
@Controller('juniors')
|
@Controller('juniors')
|
||||||
@ -59,6 +83,28 @@ export class JuniorController {
|
|||||||
return ResponseFactory.data(new JuniorResponseDto(junior));
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
@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')
|
@Post('set-theme')
|
||||||
@UseGuards(RolesGuard)
|
@UseGuards(RolesGuard)
|
||||||
@AllowedRoles(Roles.JUNIOR)
|
@AllowedRoles(Roles.JUNIOR)
|
||||||
@ -86,4 +132,96 @@ export class JuniorController {
|
|||||||
|
|
||||||
return ResponseFactory.data(new QrCodeValidationResponseDto(junior));
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':juniorId/weekly-summary')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@AllowedRoles(Roles.GUARDIAN)
|
||||||
|
@ApiDataResponse(WeeklySummaryResponseDto)
|
||||||
|
@ApiQuery({ name: 'startUtc', required: false, type: String, example: '2025-10-20T00:00:00.000Z', description: 'Start date (defaults to start of current week)' })
|
||||||
|
@ApiQuery({ name: 'endUtc', required: false, type: String, example: '2025-10-26T23:59:59.999Z', description: 'End date (defaults to end of current week)' })
|
||||||
|
async getWeeklySummary(
|
||||||
|
@Param('juniorId', CustomParseUUIDPipe) juniorId: string,
|
||||||
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
|
@Query('startUtc') startUtc?: string,
|
||||||
|
@Query('endUtc') endUtc?: string,
|
||||||
|
) {
|
||||||
|
const startDate = startUtc ? new Date(startUtc) : undefined;
|
||||||
|
const endDate = endUtc ? new Date(endUtc) : undefined;
|
||||||
|
const summary = await this.juniorService.getWeeklySummary(juniorId, user.sub, startDate, endDate);
|
||||||
|
return ResponseFactory.data(summary);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':juniorId/home')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@AllowedRoles(Roles.JUNIOR, Roles.GUARDIAN)
|
||||||
|
@ApiQuery({ name: 'size', required: false, type: Number, example: 5 })
|
||||||
|
@ApiDataResponse(JuniorHomeResponseDto)
|
||||||
|
async getJuniorHome(
|
||||||
|
@Param('juniorId', CustomParseUUIDPipe) juniorId: string,
|
||||||
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
|
@Query('size') size?: number,
|
||||||
|
) {
|
||||||
|
const limit = Math.max(1, Math.min(Number(size) || 5, 20));
|
||||||
|
const res = await this.juniorService.getJuniorHome(juniorId, user.sub, limit);
|
||||||
|
return ResponseFactory.data(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':juniorId/transfers')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@AllowedRoles(Roles.JUNIOR, Roles.GUARDIAN)
|
||||||
|
@ApiQuery({ name: 'page', required: false, type: Number, example: 1 })
|
||||||
|
@ApiQuery({ name: 'size', required: false, type: Number, example: 10 })
|
||||||
|
@ApiDataResponse(PagedChildTransfersResponseDto)
|
||||||
|
async getJuniorTransfers(
|
||||||
|
@Param('juniorId', CustomParseUUIDPipe) juniorId: string,
|
||||||
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
|
@Query('page') page?: number,
|
||||||
|
@Query('size') size?: number,
|
||||||
|
) {
|
||||||
|
const pageNum = Math.max(1, Number(page) || 1);
|
||||||
|
const pageSize = Math.max(1, Math.min(Number(size) || 10, 50));
|
||||||
|
const res = await this.juniorService.getJuniorTransfers(juniorId, user.sub, pageNum, pageSize);
|
||||||
|
return ResponseFactory.data(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':juniorId/spending-history')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@AllowedRoles(Roles.JUNIOR, Roles.GUARDIAN)
|
||||||
|
@ApiQuery({ name: 'startUtc', required: true, type: String, example: '2025-01-01T00:00:00.000Z' })
|
||||||
|
@ApiQuery({ name: 'endUtc', required: true, type: String, example: '2025-01-31T23:59:59.999Z' })
|
||||||
|
async getSpendingHistory(
|
||||||
|
@Param('juniorId', CustomParseUUIDPipe) juniorId: string,
|
||||||
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
|
@Query('startUtc') startUtc: string,
|
||||||
|
@Query('endUtc') endUtc: string,
|
||||||
|
) {
|
||||||
|
const res = await this.juniorService.getSpendingHistory(juniorId, user.sub, new Date(startUtc), new Date(endUtc));
|
||||||
|
return ResponseFactory.data(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':juniorId/transactions/:transactionId')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
@AllowedRoles(Roles.JUNIOR, Roles.GUARDIAN)
|
||||||
|
async getTransactionDetail(
|
||||||
|
@Param('juniorId', CustomParseUUIDPipe) juniorId: string,
|
||||||
|
@Param('transactionId', CustomParseUUIDPipe) transactionId: string,
|
||||||
|
@AuthenticatedUser() user: IJwtPayload,
|
||||||
|
) {
|
||||||
|
const res = await this.juniorService.getTransactionDetail(juniorId, user.sub, transactionId);
|
||||||
|
return ResponseFactory.data(res);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,2 +1,4 @@
|
|||||||
export * from './create-junior.request.dto';
|
export * from './create-junior.request.dto';
|
||||||
export * from './set-theme.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;
|
||||||
|
}
|
||||||
5
src/junior/dtos/request/update-junior.request.dto.ts
Normal file
5
src/junior/dtos/request/update-junior.request.dto.ts
Normal 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) {}
|
||||||
@ -2,3 +2,4 @@ export * from './junior.response.dto';
|
|||||||
export * from './qr-code-validation-details.response.dto';
|
export * from './qr-code-validation-details.response.dto';
|
||||||
export * from './qr-code-validation.response.dto';
|
export * from './qr-code-validation.response.dto';
|
||||||
export * from './theme.response.dto';
|
export * from './theme.response.dto';
|
||||||
|
export * from './transfer-to-junior.response.dto';
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Gender } from '~/customer/enums';
|
||||||
import { DocumentMetaResponseDto } from '~/document/dtos/response';
|
import { DocumentMetaResponseDto } from '~/document/dtos/response';
|
||||||
import { Junior } from '~/junior/entities';
|
import { Junior } from '~/junior/entities';
|
||||||
import { Relationship } from '~/junior/enums';
|
import { GuardianRelationship, Relationship } from '~/junior/enums';
|
||||||
|
|
||||||
export class JuniorResponseDto {
|
export class JuniorResponseDto {
|
||||||
@ApiProperty({ example: 'id' })
|
@ApiProperty({ example: 'id' })
|
||||||
@ -16,18 +17,35 @@ export class JuniorResponseDto {
|
|||||||
@ApiProperty({ example: 'test@junior.com' })
|
@ApiProperty({ example: 'test@junior.com' })
|
||||||
email!: string;
|
email!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: Gender.MALE })
|
||||||
|
gender!: Gender;
|
||||||
|
|
||||||
|
@ApiProperty({ example: '2000-01-01' })
|
||||||
|
dateOfBirth!: Date;
|
||||||
|
|
||||||
@ApiProperty({ enum: Relationship })
|
@ApiProperty({ enum: Relationship })
|
||||||
relationship!: Relationship;
|
relationship!: Relationship;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: GuardianRelationship })
|
||||||
|
guardianRelationship!: GuardianRelationship;
|
||||||
|
|
||||||
@ApiProperty({ type: DocumentMetaResponseDto })
|
@ApiProperty({ type: DocumentMetaResponseDto })
|
||||||
profilePicture!: DocumentMetaResponseDto | null;
|
profilePicture!: DocumentMetaResponseDto | null;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 2000.0, description: 'The available balance' })
|
||||||
|
availableBalance!: number | null;
|
||||||
|
|
||||||
constructor(junior: Junior) {
|
constructor(junior: Junior) {
|
||||||
|
const card = junior.customer?.cards?.[0];
|
||||||
this.id = junior.id;
|
this.id = junior.id;
|
||||||
this.firstName = junior.customer.firstName;
|
this.firstName = junior.customer.firstName;
|
||||||
this.lastName = junior.customer.lastName;
|
this.lastName = junior.customer.lastName;
|
||||||
this.email = junior.customer.user.email;
|
this.email = junior.customer.user.email;
|
||||||
|
this.gender = junior.customer.gender;
|
||||||
|
this.dateOfBirth = junior.customer.dateOfBirth;
|
||||||
this.relationship = junior.relationship;
|
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
|
this.profilePicture = junior.customer.user.profilePicture
|
||||||
? new DocumentMetaResponseDto(junior.customer.user.profilePicture)
|
? new DocumentMetaResponseDto(junior.customer.user.profilePicture)
|
||||||
: null;
|
: null;
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { Gender } from '~/customer/enums';
|
||||||
import { Guardian } from '~/guardian/entities/guradian.entity';
|
import { Guardian } from '~/guardian/entities/guradian.entity';
|
||||||
import { Junior } from '~/junior/entities';
|
import { Junior } from '~/junior/entities';
|
||||||
import { GuardianRelationship } from '~/junior/enums';
|
import { ChildRelationshipLabel, GuardianRelationship, Relationship } from '~/junior/enums';
|
||||||
|
|
||||||
export class QrCodeValidationDetailsResponse {
|
export class QrCodeValidationDetailsResponse {
|
||||||
@ApiProperty()
|
@ApiProperty()
|
||||||
@ -26,6 +27,17 @@ export class QrCodeValidationDetailsResponse {
|
|||||||
this.phoneNumber = person.customer.user.phoneNumber;
|
this.phoneNumber = person.customer.user.phoneNumber;
|
||||||
this.email = person.customer.user.email;
|
this.email = person.customer.user.email;
|
||||||
this.dateOfBirth = person.customer.dateOfBirth;
|
this.dateOfBirth = person.customer.dateOfBirth;
|
||||||
this.relationship = guardian ? junior.relationship : GuardianRelationship[junior.relationship];
|
|
||||||
|
if (guardian) {
|
||||||
|
this.relationship = junior.relationship;
|
||||||
|
} else {
|
||||||
|
if (junior.relationship === Relationship.PARENT) {
|
||||||
|
this.relationship = junior.customer.gender === Gender.MALE
|
||||||
|
? ChildRelationshipLabel.SON
|
||||||
|
: ChildRelationshipLabel.DAUGHTER;
|
||||||
|
} else {
|
||||||
|
this.relationship = GuardianRelationship[junior.relationship];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
31
src/junior/dtos/response/weekly-summary.response.dto.ts
Normal file
31
src/junior/dtos/response/weekly-summary.response.dto.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class WeeklySummaryResponseDto {
|
||||||
|
@ApiProperty({ description: 'Start date of the week', example: '2023-10-01' })
|
||||||
|
startOfWeek!: Date;
|
||||||
|
@ApiProperty({ description: 'End date of the week', example: '2023-10-07' })
|
||||||
|
endOfWeek!: Date;
|
||||||
|
@ApiProperty({ description: 'Total amount spent in the week', example: 350 })
|
||||||
|
total!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Amount spent on Sunday', example: 50 })
|
||||||
|
sunday!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Amount spent on Monday', example: 30 })
|
||||||
|
monday!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Amount spent on Tuesday', example: 20 })
|
||||||
|
tuesday!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Amount spent on Wednesday', example: 40 })
|
||||||
|
wednesday!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Amount spent on Thursday', example: 60 })
|
||||||
|
thursday!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Amount spent on Friday', example: 70 })
|
||||||
|
friday!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ description: 'Amount spent on Saturday', example: 80 })
|
||||||
|
saturday!: number;
|
||||||
|
}
|
||||||
@ -2,15 +2,18 @@ import {
|
|||||||
BaseEntity,
|
BaseEntity,
|
||||||
Column,
|
Column,
|
||||||
CreateDateColumn,
|
CreateDateColumn,
|
||||||
|
DeleteDateColumn,
|
||||||
Entity,
|
Entity,
|
||||||
JoinColumn,
|
JoinColumn,
|
||||||
ManyToOne,
|
ManyToOne,
|
||||||
|
OneToMany,
|
||||||
OneToOne,
|
OneToOne,
|
||||||
PrimaryColumn,
|
PrimaryColumn,
|
||||||
UpdateDateColumn,
|
UpdateDateColumn,
|
||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
import { Customer } from '~/customer/entities';
|
import { Customer } from '~/customer/entities';
|
||||||
import { Guardian } from '~/guardian/entities/guradian.entity';
|
import { Guardian } from '~/guardian/entities/guradian.entity';
|
||||||
|
import { MoneyRequest } from '~/money-request/entities/money-request.entity';
|
||||||
import { Relationship } from '../enums';
|
import { Relationship } from '../enums';
|
||||||
import { Theme } from './theme.entity';
|
import { Theme } from './theme.entity';
|
||||||
|
|
||||||
@ -39,9 +42,15 @@ export class Junior extends BaseEntity {
|
|||||||
@JoinColumn({ name: 'guardian_id' })
|
@JoinColumn({ name: 'guardian_id' })
|
||||||
guardian!: Guardian;
|
guardian!: Guardian;
|
||||||
|
|
||||||
|
@OneToMany(() => MoneyRequest, (moneyRequest) => moneyRequest.junior)
|
||||||
|
moneyRequests!: MoneyRequest[];
|
||||||
|
|
||||||
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
@CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
createdAt!: Date;
|
createdAt!: Date;
|
||||||
|
|
||||||
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', default: () => 'CURRENT_TIMESTAMP' })
|
||||||
updatedAt!: Date;
|
updatedAt!: Date;
|
||||||
|
|
||||||
|
@DeleteDateColumn({ name: 'deleted_at', type: 'timestamp with time zone', nullable: true })
|
||||||
|
deletedAt!: Date | null;
|
||||||
}
|
}
|
||||||
|
|||||||
5
src/junior/enums/child-relationship-label.enum.ts
Normal file
5
src/junior/enums/child-relationship-label.enum.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export enum ChildRelationshipLabel {
|
||||||
|
SON = 'SON',
|
||||||
|
DAUGHTER = 'DAUGHTER',
|
||||||
|
}
|
||||||
|
|
||||||
@ -1,3 +1,4 @@
|
|||||||
|
export * from './child-relationship-label.enum';
|
||||||
export * from './guardian-relationship.enum';
|
export * from './guardian-relationship.enum';
|
||||||
export * from './relationship.enum';
|
export * from './relationship.enum';
|
||||||
export * from './theme-color.enum';
|
export * from './theme-color.enum';
|
||||||
|
|||||||
@ -13,14 +13,28 @@ export class JuniorRepository {
|
|||||||
findJuniorsByGuardianId(guardianId: string, pageOptions: PageOptionsRequestDto) {
|
findJuniorsByGuardianId(guardianId: string, pageOptions: PageOptionsRequestDto) {
|
||||||
return this.juniorRepository.findAndCount({
|
return this.juniorRepository.findAndCount({
|
||||||
where: { guardianId },
|
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,
|
skip: (pageOptions.page - FIRST_PAGE) * pageOptions.size,
|
||||||
take: pageOptions.size,
|
take: pageOptions.size,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
findJuniorById(juniorId: string, withGuardianRelation = false, guardianId?: string) {
|
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) {
|
if (withGuardianRelation) {
|
||||||
relations.push('guardian', 'guardian.customer', 'guardian.customer.user');
|
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,18 +1,26 @@
|
|||||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { IsNull, Not } from 'typeorm';
|
||||||
import { Transactional } from 'typeorm-transactional';
|
import { Transactional } from 'typeorm-transactional';
|
||||||
import { Roles } from '~/auth/enums';
|
import { Roles } from '~/auth/enums';
|
||||||
import { CardService } from '~/card/services';
|
import { CardService, TransactionService } from '~/card/services';
|
||||||
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
import { NeoLeapService } from '~/common/modules/neoleap/services';
|
||||||
import { PageOptionsRequestDto } from '~/core/dtos';
|
import { PageOptionsRequestDto } from '~/core/dtos';
|
||||||
|
import { setIf } from '~/core/utils';
|
||||||
import { CustomerService } from '~/customer/services';
|
import { CustomerService } from '~/customer/services';
|
||||||
import { DocumentService, OciService } from '~/document/services';
|
import { DocumentService, OciService } from '~/document/services';
|
||||||
import { UserType } from '~/user/enums';
|
import { UserType } from '~/user/enums';
|
||||||
import { UserService } from '~/user/services';
|
import { UserService } from '~/user/services';
|
||||||
import { UserTokenService } from '~/user/services/user-token.service';
|
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 { Junior } from '../entities';
|
||||||
import { JuniorRepository } from '../repositories';
|
import { JuniorRepository } from '../repositories';
|
||||||
import { QrcodeService } from './qrcode.service';
|
import { QrcodeService } from './qrcode.service';
|
||||||
|
import { JuniorHomeResponseDto, PagedChildTransfersResponseDto } from '~/card/dtos/responses';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class JuniorService {
|
export class JuniorService {
|
||||||
@ -27,6 +35,7 @@ export class JuniorService {
|
|||||||
private readonly qrCodeService: QrcodeService,
|
private readonly qrCodeService: QrcodeService,
|
||||||
private readonly neoleapService: NeoLeapService,
|
private readonly neoleapService: NeoLeapService,
|
||||||
private readonly cardService: CardService,
|
private readonly cardService: CardService,
|
||||||
|
private readonly transactionService: TransactionService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
@ -85,6 +94,40 @@ export class JuniorService {
|
|||||||
return junior;
|
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(customer, 'gender', body.gender);
|
||||||
|
|
||||||
|
setIf(junior, 'relationship', body.relationship);
|
||||||
|
await Promise.all([junior.save(), customer.save(), user.save()]);
|
||||||
|
this.logger.log(`Junior ${juniorId} updated successfully`);
|
||||||
|
return junior;
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
async setTheme(body: SetThemeRequestDto, juniorId: string) {
|
async setTheme(body: SetThemeRequestDto, juniorId: string) {
|
||||||
this.logger.log(`Setting theme for junior ${juniorId}`);
|
this.logger.log(`Setting theme for junior ${juniorId}`);
|
||||||
@ -133,6 +176,140 @@ export class JuniorService {
|
|||||||
return !!junior;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getWeeklySummary(juniorId: string, guardianId: string, startDate?: Date, endDate?: Date) {
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(`Getting weekly summary for junior ${juniorId}`);
|
||||||
|
return this.cardService.getWeeklySummary(juniorId, startDate, endDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getJuniorHome(juniorId: string, userId: string, size: number): Promise<JuniorHomeResponseDto> {
|
||||||
|
this.logger.log(`Getting home for junior ${juniorId}`);
|
||||||
|
|
||||||
|
// Check if user is the junior themselves or their guardian
|
||||||
|
let junior: Junior | null;
|
||||||
|
if (juniorId === userId) {
|
||||||
|
// User is the junior accessing their own home
|
||||||
|
junior = await this.findJuniorById(juniorId, false);
|
||||||
|
} else {
|
||||||
|
// User might be the guardian accessing junior's home
|
||||||
|
junior = await this.findJuniorById(juniorId, false, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!junior) {
|
||||||
|
throw new BadRequestException('JUNIOR.NOT_FOUND');
|
||||||
|
}
|
||||||
|
|
||||||
|
const card = junior.customer?.cards?.[0];
|
||||||
|
const availableBalance = card ? Math.min(card.limit, card.account.balance) : 0;
|
||||||
|
|
||||||
|
const recentTransfers = await this.transactionService.getChildTransfers(juniorId, 1, size);
|
||||||
|
|
||||||
|
return new JuniorHomeResponseDto(availableBalance, recentTransfers);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getJuniorTransfers(
|
||||||
|
juniorId: string,
|
||||||
|
userId: string,
|
||||||
|
page: number,
|
||||||
|
size: number,
|
||||||
|
): Promise<PagedChildTransfersResponseDto> {
|
||||||
|
this.logger.log(`Getting transfers for junior ${juniorId}`);
|
||||||
|
|
||||||
|
// Check if user is the junior themselves or their guardian
|
||||||
|
let junior: Junior | null;
|
||||||
|
if (juniorId === userId) {
|
||||||
|
// User is the junior accessing their own transfers
|
||||||
|
junior = await this.findJuniorById(juniorId, false);
|
||||||
|
} else {
|
||||||
|
// User might be the guardian accessing junior's transfers
|
||||||
|
junior = await this.findJuniorById(juniorId, false, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!junior) {
|
||||||
|
throw new BadRequestException('JUNIOR.NOT_FOUND');
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.transactionService.getChildTransfersPaginated(juniorId, page, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSpendingHistory(juniorId: string, userId: string, startUtc: Date, endUtc: Date) {
|
||||||
|
this.logger.log(`Getting spending history for junior ${juniorId}`);
|
||||||
|
|
||||||
|
// Check if user is the junior themselves or their guardian
|
||||||
|
let junior: Junior | null;
|
||||||
|
if (juniorId === userId) {
|
||||||
|
junior = await this.findJuniorById(juniorId, false);
|
||||||
|
} else {
|
||||||
|
junior = await this.findJuniorById(juniorId, false, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!junior) {
|
||||||
|
throw new BadRequestException('JUNIOR.NOT_FOUND');
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.transactionService.getChildSpendingHistory(juniorId, startUtc, endUtc);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTransactionDetail(juniorId: string, userId: string, transactionId: string) {
|
||||||
|
this.logger.log(`Getting transaction detail ${transactionId} for junior ${juniorId}`);
|
||||||
|
|
||||||
|
// Check if user is the junior themselves or their guardian
|
||||||
|
let junior: Junior | null;
|
||||||
|
if (juniorId === userId) {
|
||||||
|
junior = await this.findJuniorById(juniorId, false);
|
||||||
|
} else {
|
||||||
|
junior = await this.findJuniorById(juniorId, false, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!junior) {
|
||||||
|
throw new BadRequestException('JUNIOR.NOT_FOUND');
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.transactionService.getTransactionDetail(transactionId, juniorId);
|
||||||
|
}
|
||||||
|
|
||||||
private async prepareJuniorImages(juniors: Junior[]) {
|
private async prepareJuniorImages(juniors: Junior[]) {
|
||||||
this.logger.log(`Preparing junior images`);
|
this.logger.log(`Preparing junior images`);
|
||||||
await Promise.all(
|
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);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,6 +1,7 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
import { IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
|
import { IsDateString, IsEmail, IsEnum, IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
|
||||||
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
import { i18nValidationMessage as i18n } from 'nestjs-i18n';
|
||||||
|
import { Gender } from '~/customer/enums';
|
||||||
export class UpdateUserRequestDto {
|
export class UpdateUserRequestDto {
|
||||||
@ApiProperty({ example: 'John' })
|
@ApiProperty({ example: 'John' })
|
||||||
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'user.firstName' }) })
|
@IsString({ message: i18n('validation.IsString', { path: 'general', property: 'user.firstName' }) })
|
||||||
@ -14,8 +15,23 @@ export class UpdateUserRequestDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
lastName!: string;
|
lastName!: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 'child@example.com' })
|
||||||
|
@IsEmail({}, { message: i18n('validation.IsEmail', { path: 'general', property: 'user.email' }) })
|
||||||
|
@IsOptional()
|
||||||
|
email!: string;
|
||||||
|
|
||||||
@ApiProperty({ example: '123e4567-e89b-12d3-a456-426614174000' })
|
@ApiProperty({ example: '123e4567-e89b-12d3-a456-426614174000' })
|
||||||
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'user.profilePictureId' }) })
|
@IsUUID('4', { message: i18n('validation.IsUUID', { path: 'general', property: 'user.profilePictureId' }) })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
profilePictureId!: string;
|
profilePictureId!: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: Gender })
|
||||||
|
@IsEnum(Gender, { message: i18n('validation.IsEnum', { path: 'general', property: 'customer.gender' }) })
|
||||||
|
@IsOptional()
|
||||||
|
gender!: Gender;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: '2020-01-01' })
|
||||||
|
@IsDateString({}, { message: i18n('validation.IsDateString', { path: 'general', property: 'customer.dateOfBirth' }) })
|
||||||
|
@IsOptional()
|
||||||
|
dateOfBirth!: Date;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -28,7 +28,7 @@ export class User extends BaseEntity {
|
|||||||
@Column('varchar', { length: 255, name: 'last_name', nullable: false })
|
@Column('varchar', { length: 255, name: 'last_name', nullable: false })
|
||||||
lastName!: string;
|
lastName!: string;
|
||||||
|
|
||||||
@Column('varchar', { length: 255, name: 'email', nullable: true })
|
@Column('varchar', { length: 255, name: 'email', nullable: true, unique: true })
|
||||||
email!: string;
|
email!: string;
|
||||||
|
|
||||||
@Column('varchar', { length: 255, name: 'phone_number', nullable: true })
|
@Column('varchar', { length: 255, name: 'phone_number', nullable: true })
|
||||||
|
|||||||
@ -191,16 +191,38 @@ export class UserService {
|
|||||||
async updateUser(userId: string, data: UpdateUserRequestDto) {
|
async updateUser(userId: string, data: UpdateUserRequestDto) {
|
||||||
await this.validateProfilePictureId(data.profilePictureId, userId);
|
await this.validateProfilePictureId(data.profilePictureId, userId);
|
||||||
|
|
||||||
|
if (data.email) {
|
||||||
|
const userWithEmail = await this.findUser({ email: data.email });
|
||||||
|
if (userWithEmail && userWithEmail.id !== userId) {
|
||||||
|
this.logger.error(`Email ${data.email} is already taken by another user`);
|
||||||
|
throw new BadRequestException('USER.EMAIL_ALREADY_TAKEN');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.logger.log(`Updating user ${userId} with data ${JSON.stringify(data)}`);
|
this.logger.log(`Updating user ${userId} with data ${JSON.stringify(data)}`);
|
||||||
const { affected } = await this.userRepository.update(userId, data);
|
|
||||||
|
const { gender, dateOfBirth, ...userData } = data;
|
||||||
|
|
||||||
|
const { affected } = await this.userRepository.update(userId, userData);
|
||||||
if (affected === 0) {
|
if (affected === 0) {
|
||||||
this.logger.error(`User with id ${userId} not found`);
|
this.logger.error(`User with id ${userId} not found`);
|
||||||
throw new BadRequestException('USER.NOT_FOUND');
|
throw new BadRequestException('USER.NOT_FOUND');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (gender !== undefined || dateOfBirth !== undefined) {
|
||||||
|
const customerData: Partial<{ gender: typeof gender; dateOfBirth: Date }> = {};
|
||||||
|
if (gender !== undefined) {
|
||||||
|
customerData.gender = gender;
|
||||||
|
}
|
||||||
|
if (dateOfBirth !== undefined) {
|
||||||
|
customerData.dateOfBirth = dateOfBirth;
|
||||||
|
}
|
||||||
|
await this.customerService.updateCustomer(userId, customerData);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateUserEmail(userId: string, email: string) {
|
async updateUserEmail(userId: string, email: string) {
|
||||||
const userWithEmail = await this.findUser({ email, isEmailVerified: true });
|
const userWithEmail = await this.findUser({ email });
|
||||||
|
|
||||||
if (userWithEmail) {
|
if (userWithEmail) {
|
||||||
if (userWithEmail.id === userId) {
|
if (userWithEmail.id === userId) {
|
||||||
|
|||||||
Reference in New Issue
Block a user