mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-11-26 16:44:54 +00:00
Compare commits
59 Commits
872d231f72
...
feat/neole
| Author | SHA1 | Date | |
|---|---|---|---|
| fc57bfa721 | |||
| 2a62787c3b | |||
| 91dea22f45 | |||
| ef28c75f9b | |||
| c007ac584f | |||
| d2d83549b2 | |||
| 506974afc8 | |||
| 95f8cfbfdf | |||
| 8b00cda23d | |||
| 12cc88a50e | |||
| 2172051093 | |||
| a6a573957c | |||
| d6fb5f48d9 | |||
| b0011eb7cc | |||
| 99af65a300 | |||
| 0c9b40132a | |||
| e66c0f120c | |||
| 3b295ea79f | |||
| 5ffe18ede3 | |||
| 7194c38918 | |||
| a3a61b4923 | |||
| 39d5fc1869 | |||
| 05a6ad2d84 | |||
| 5649d24724 | |||
| 9d9408dedd | |||
| 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 | |||
| 11712bedf3 |
@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -34,6 +34,15 @@ export class CardsController {
|
|||||||
return ResponseFactory.data(cards.map((card) => new ChildCardResponseDto(card)));
|
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')
|
@Get('child-cards/:cardid/embossing-details')
|
||||||
@UseGuards(RolesGuard)
|
@UseGuards(RolesGuard)
|
||||||
@AllowedRoles(Roles.GUARDIAN)
|
@AllowedRoles(Roles.GUARDIAN)
|
||||||
|
|||||||
@ -58,7 +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;
|
this.reservedBalance = card.customerType === CustomerType.PARENT ? card.account.reservedBalance : 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,3 +1,15 @@
|
|||||||
export * from './account-iban.response.dto';
|
export * from './account-iban.response.dto';
|
||||||
export * from './card.response.dto';
|
export * from './card.response.dto';
|
||||||
export * from './child-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,10 +22,28 @@ 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' })
|
@Column('decimal', {
|
||||||
|
precision: 10,
|
||||||
|
scale: 2,
|
||||||
|
default: 0.0,
|
||||||
|
name: 'reserved_balance',
|
||||||
|
transformer: {
|
||||||
|
to: (value: number) => value,
|
||||||
|
from: (value: string) => parseFloat(value),
|
||||||
|
},
|
||||||
|
})
|
||||||
reservedBalance!: number;
|
reservedBalance!: number;
|
||||||
|
|
||||||
@OneToMany(() => Card, (card) => card.account, { cascade: true })
|
@OneToMany(() => Card, (card) => card.account, { cascade: true })
|
||||||
|
|||||||
@ -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',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -45,6 +45,13 @@ export class CardRepository {
|
|||||||
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'] });
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -84,4 +87,97 @@ export class TransactionRepository {
|
|||||||
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -64,9 +64,8 @@ export class AccountService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
increaseReservedBalance(account: Account, amount: number) {
|
increaseReservedBalance(account: Account, amount: number) {
|
||||||
if (account.balance < account.reservedBalance + amount) {
|
// Balance check is performed by the caller (e.g., transferToChild)
|
||||||
throw new UnprocessableEntityException('ACCOUNT.INSUFFICIENT_BALANCE');
|
// to ensure correct account (guardian vs child) is validated
|
||||||
}
|
|
||||||
return this.accountRepository.increaseReservedBalance(account.id, amount);
|
return this.accountRepository.increaseReservedBalance(account.id, amount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -63,6 +63,15 @@ export class CardService {
|
|||||||
|
|
||||||
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);
|
||||||
|
|
||||||
@ -139,7 +148,18 @@ export class CardService {
|
|||||||
async transferToChild(juniorId: string, amount: number) {
|
async transferToChild(juniorId: string, amount: number) {
|
||||||
const card = await this.getCardByCustomerId(juniorId);
|
const card = await this.getCardByCustomerId(juniorId);
|
||||||
|
|
||||||
if (amount > card.account.balance - card.account.reservedBalance) {
|
this.logger.debug(`Transfer to child - juniorId: ${juniorId}, parentId: ${card.parentId}, cardId: ${card.id}`);
|
||||||
|
this.logger.debug(`Card account - balance: ${card.account.balance}, reserved: ${card.account.reservedBalance}`);
|
||||||
|
|
||||||
|
const fundingAccount = card.parentId
|
||||||
|
? await this.accountService.getAccountByCustomerId(card.parentId)
|
||||||
|
: card.account;
|
||||||
|
|
||||||
|
this.logger.debug(`Funding account - balance: ${fundingAccount.balance}, reserved: ${fundingAccount.reservedBalance}, available: ${fundingAccount.balance - fundingAccount.reservedBalance}`);
|
||||||
|
this.logger.debug(`Amount requested: ${amount}`);
|
||||||
|
|
||||||
|
if (amount > fundingAccount.balance - fundingAccount.reservedBalance) {
|
||||||
|
this.logger.error(`Insufficient balance - requested: ${amount}, available: ${fundingAccount.balance - fundingAccount.reservedBalance}`);
|
||||||
throw new BadRequestException('CARD.INSUFFICIENT_BALANCE');
|
throw new BadRequestException('CARD.INSUFFICIENT_BALANCE');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -147,13 +167,17 @@ export class CardService {
|
|||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.neoleapService.updateCardControl(card.cardReference, finalAmount.toNumber()),
|
this.neoleapService.updateCardControl(card.cardReference, finalAmount.toNumber()),
|
||||||
this.updateCardLimit(card.id, finalAmount.toNumber()),
|
this.updateCardLimit(card.id, finalAmount.toNumber()),
|
||||||
this.accountService.increaseReservedBalance(card.account, amount),
|
this.accountService.increaseReservedBalance(fundingAccount, amount),
|
||||||
this.transactionService.createInternalChildTransaction(card.id, amount),
|
this.transactionService.createInternalChildTransaction(card.id, amount),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return finalAmount.toNumber();
|
return finalAmount.toNumber();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getWeeklySummary(juniorId: string, startDate?: Date, endDate?: Date) {
|
||||||
|
return this.transactionService.getWeeklySummary(juniorId, startDate, endDate);
|
||||||
|
}
|
||||||
|
|
||||||
fundIban(iban: string, amount: number) {
|
fundIban(iban: string, amount: number) {
|
||||||
return this.accountService.fundIban(iban, amount);
|
return this.accountService.fundIban(iban, amount);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1 +1,3 @@
|
|||||||
export * from './card.service';
|
export * from './card.service';
|
||||||
|
export * from './transaction.service';
|
||||||
|
export * from './account.service';
|
||||||
|
|||||||
@ -1,15 +1,25 @@
|
|||||||
import { forwardRef, Inject, 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 } from '../enums';
|
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 {
|
||||||
@ -32,10 +42,18 @@ export class TransactionService {
|
|||||||
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) {
|
if (card.customerType === CustomerType.CHILD) {
|
||||||
|
if (card.parentId) {
|
||||||
|
const parentAccount = await this.accountService.getAccountByCustomerId(card.parentId);
|
||||||
|
await Promise.all([
|
||||||
|
this.accountService.decreaseAccountBalance(parentAccount.accountReference, total.toNumber()),
|
||||||
|
this.accountService.decrementReservedBalance(parentAccount, total.toNumber()),
|
||||||
|
]);
|
||||||
|
} else {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber()),
|
this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber()),
|
||||||
this.accountService.decrementReservedBalance(card.account, total.toNumber()),
|
this.accountService.decrementReservedBalance(card.account, total.toNumber()),
|
||||||
]);
|
]);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
await this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber());
|
await this.accountService.decreaseAccountBalance(card.account.accountReference, total.toNumber());
|
||||||
}
|
}
|
||||||
@ -73,4 +91,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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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;
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { IJwtPayload } from '~/auth/interfaces';
|
import { IJwtPayload } from '~/auth/interfaces';
|
||||||
import { AuthenticatedUser } from '~/common/decorators';
|
import { AuthenticatedUser } from '~/common/decorators';
|
||||||
import { AccessTokenGuard } from '~/common/guards';
|
import { AccessTokenGuard } from '~/common/guards';
|
||||||
import { ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
|
import { ApiDataResponse, ApiLangRequestHeader } from '~/core/decorators';
|
||||||
import { ResponseFactory } from '~/core/utils';
|
import { ResponseFactory } from '~/core/utils';
|
||||||
import { InitiateKycRequestDto } from '../dtos/request';
|
import { InitiateKycRequestDto } from '../dtos/request';
|
||||||
import { CustomerResponseDto, InitiateKycResponseDto } from '../dtos/response';
|
import { CustomerResponseDto, InitiateKycResponseDto, KycMetadataResponseDto } from '../dtos/response';
|
||||||
import { CustomerService } from '../services';
|
import { CustomerService } from '../services';
|
||||||
|
|
||||||
@Controller('customers')
|
@Controller('customers')
|
||||||
@ -32,4 +32,14 @@ export class CustomerController {
|
|||||||
|
|
||||||
return ResponseFactory.data(new InitiateKycResponseDto(res.randomNumber));
|
return ResponseFactory.data(new InitiateKycResponseDto(res.randomNumber));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('/kyc/onboard-metadata')
|
||||||
|
@UseGuards(AccessTokenGuard)
|
||||||
|
@ApiOperation({ summary: 'Get KYC onboarding form metadata' })
|
||||||
|
@ApiDataResponse(KycMetadataResponseDto)
|
||||||
|
async getKycMetadata() {
|
||||||
|
const metadata = await this.customerService.getKycOnboardMetadata();
|
||||||
|
|
||||||
|
return ResponseFactory.data(metadata);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,12 +6,12 @@ import { UserModule } from '~/user/user.module';
|
|||||||
import { CustomerController } from './controllers';
|
import { CustomerController } from './controllers';
|
||||||
import { Customer } from './entities';
|
import { Customer } from './entities';
|
||||||
import { CustomerRepository } from './repositories/customer.repository';
|
import { CustomerRepository } from './repositories/customer.repository';
|
||||||
import { CustomerService } from './services';
|
import { CustomerService, MetadataService } from './services';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Customer]), GuardianModule, forwardRef(() => UserModule), NeoLeapModule],
|
imports: [TypeOrmModule.forFeature([Customer]), GuardianModule, forwardRef(() => UserModule), NeoLeapModule],
|
||||||
controllers: [CustomerController],
|
controllers: [CustomerController],
|
||||||
providers: [CustomerService, CustomerRepository],
|
providers: [CustomerService, CustomerRepository, MetadataService],
|
||||||
exports: [CustomerService],
|
exports: [CustomerService],
|
||||||
})
|
})
|
||||||
export class CustomerModule {}
|
export class CustomerModule {}
|
||||||
|
|||||||
@ -1,2 +1,3 @@
|
|||||||
export * from './customer.response.dto';
|
export * from './customer.response.dto';
|
||||||
export * from './initiate-kyc.response.dto';
|
export * from './initiate-kyc.response.dto';
|
||||||
|
export * from './kyc-metadata.response.dto';
|
||||||
|
|||||||
12
src/customer/dtos/response/kyc-metadata.response.dto.ts
Normal file
12
src/customer/dtos/response/kyc-metadata.response.dto.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
export class MetadataOptionDto {
|
||||||
|
value!: string;
|
||||||
|
label!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class KycMetadataResponseDto {
|
||||||
|
poiTypes!: MetadataOptionDto[];
|
||||||
|
jobSectors!: MetadataOptionDto[];
|
||||||
|
incomeSources!: MetadataOptionDto[];
|
||||||
|
jobCategories!: MetadataOptionDto[];
|
||||||
|
incomeRanges!: MetadataOptionDto[];
|
||||||
|
}
|
||||||
8
src/customer/enums/income-range.enum.ts
Normal file
8
src/customer/enums/income-range.enum.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
export enum IncomeRange {
|
||||||
|
BELOW_2000 = 'SAR 2,000 and below',
|
||||||
|
RANGE_2000_5000 = 'SAR 2,000 to 5,000',
|
||||||
|
RANGE_5000_10000 = 'SAR 5,000 to 10,000',
|
||||||
|
RANGE_10000_20000 = 'SAR 10,000 to 20,000',
|
||||||
|
ABOVE_20000 = 'SAR 20,000 and above',
|
||||||
|
}
|
||||||
|
|
||||||
9
src/customer/enums/income-source.enum.ts
Normal file
9
src/customer/enums/income-source.enum.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
export enum IncomeSource {
|
||||||
|
SALARY = 'SALARY',
|
||||||
|
ANCESTRAL = 'ANCESTRAL',
|
||||||
|
REAL_ESTATE = 'REAL_ESTATE',
|
||||||
|
INVESTMENT_RETURNS = 'INVESTMENT_RETURNS',
|
||||||
|
RENTAL_INCOME = 'RENTAL_INCOME',
|
||||||
|
OTHER = 'OTHER',
|
||||||
|
}
|
||||||
|
|
||||||
@ -1,3 +1,8 @@
|
|||||||
export * from './customer-status.enum';
|
export * from './customer-status.enum';
|
||||||
export * from './gender.enum';
|
export * from './gender.enum';
|
||||||
export * from './kyc-status.enum';
|
export * from './kyc-status.enum';
|
||||||
|
export * from './poi-type.enum';
|
||||||
|
export * from './job-sector.enum';
|
||||||
|
export * from './income-source.enum';
|
||||||
|
export * from './job-category.enum';
|
||||||
|
export * from './income-range.enum';
|
||||||
|
|||||||
57
src/customer/enums/job-category.enum.ts
Normal file
57
src/customer/enums/job-category.enum.ts
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
export enum JobCategory {
|
||||||
|
ASSISTANT_MINISTER = 'ASSISTANT_MINISTER',
|
||||||
|
DEPUTY_MINISTER = 'DEPUTY_MINISTER',
|
||||||
|
UNDER_SECRETARY = 'UNDER_SECRETARY',
|
||||||
|
GENERAL_MANAGER = 'GENERAL_MANAGER',
|
||||||
|
CHAIRMAN = 'CHAIRMAN',
|
||||||
|
MANAGER = 'MANAGER',
|
||||||
|
PROFESSOR = 'PROFESSOR',
|
||||||
|
HEAD_OF_COURT = 'HEAD_OF_COURT',
|
||||||
|
JUDGE = 'JUDGE',
|
||||||
|
LAWYER = 'LAWYER',
|
||||||
|
SCIENTIST = 'SCIENTIST',
|
||||||
|
NOTARY = 'NOTARY',
|
||||||
|
BUSINESSMAN = 'BUSINESSMAN',
|
||||||
|
MERCHANT = 'MERCHANT',
|
||||||
|
PHARMACIST = 'PHARMACIST',
|
||||||
|
DOCTOR = 'DOCTOR',
|
||||||
|
MEDICAL_TECHNICIAN = 'MEDICAL_TECHNICIAN',
|
||||||
|
NURSE = 'NURSE',
|
||||||
|
ENGINEER = 'ENGINEER',
|
||||||
|
CHEMIST = 'CHEMIST',
|
||||||
|
CONTRACTOR = 'CONTRACTOR',
|
||||||
|
AUDITOR_ACCOUNTANT = 'AUDITOR_ACCOUNTANT',
|
||||||
|
RESEARCHER = 'RESEARCHER',
|
||||||
|
ACCOUNTANT = 'ACCOUNTANT',
|
||||||
|
JOURNALIST = 'JOURNALIST',
|
||||||
|
DESIGNER = 'DESIGNER',
|
||||||
|
COMPUTER_SPECIALIST = 'COMPUTER_SPECIALIST',
|
||||||
|
TRANSLATOR = 'TRANSLATOR',
|
||||||
|
TEACHER = 'TEACHER',
|
||||||
|
PILOT = 'PILOT',
|
||||||
|
HOST = 'HOST',
|
||||||
|
OFFICER = 'OFFICER',
|
||||||
|
SOLDIER = 'SOLDIER',
|
||||||
|
RETIRED = 'RETIRED',
|
||||||
|
SALESMAN = 'SALESMAN',
|
||||||
|
AUTHOR = 'AUTHOR',
|
||||||
|
CRAFTSMAN = 'CRAFTSMAN',
|
||||||
|
SECURITY = 'SECURITY',
|
||||||
|
LABORER = 'LABORER',
|
||||||
|
DRIVER = 'DRIVER',
|
||||||
|
FARMER = 'FARMER',
|
||||||
|
HOUSEWIFE = 'HOUSEWIFE',
|
||||||
|
DIPLOMAT = 'DIPLOMAT',
|
||||||
|
STUDENT = 'STUDENT',
|
||||||
|
FREELANCER = 'FREELANCER',
|
||||||
|
SHEPHERD = 'SHEPHERD',
|
||||||
|
HOUSEMAID_OR_BABYSITTER = 'HOUSEMAID_OR_BABYSITTER',
|
||||||
|
CAPTAIN = 'CAPTAIN',
|
||||||
|
AMBASSADOR = 'AMBASSADOR',
|
||||||
|
MARKETING = 'MARKETING',
|
||||||
|
CONSULTING = 'CONSULTING',
|
||||||
|
SUPERVISOR = 'SUPERVISOR',
|
||||||
|
BANKER = 'BANKER',
|
||||||
|
BODYGUARD_OR_PERSONAL_ASSISTANT = 'BODYGUARD_OR_PERSONAL_ASSISTANT',
|
||||||
|
}
|
||||||
|
|
||||||
12
src/customer/enums/job-sector.enum.ts
Normal file
12
src/customer/enums/job-sector.enum.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
export enum JobSector {
|
||||||
|
GOVERNMENT_SECTOR = 'GOVERNMENT_SECTOR',
|
||||||
|
HOME_MAKER = 'HOME_MAKER',
|
||||||
|
MILITARY = 'MILITARY',
|
||||||
|
PRIVATE_SECTOR = 'PRIVATE_SECTOR',
|
||||||
|
RETIRED = 'RETIRED',
|
||||||
|
SELF_EMPLOYED = 'SELF_EMPLOYED',
|
||||||
|
STUDENT = 'STUDENT',
|
||||||
|
HOUSEHOLD_LABOR = 'HOUSEHOLD_LABOR',
|
||||||
|
UNEMPLOYED = 'UNEMPLOYED',
|
||||||
|
}
|
||||||
|
|
||||||
5
src/customer/enums/poi-type.enum.ts
Normal file
5
src/customer/enums/poi-type.enum.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export enum PoiType {
|
||||||
|
IQA = 'IQA', // Iqama (Resident ID)
|
||||||
|
NAT = 'NAT', // National ID
|
||||||
|
}
|
||||||
|
|
||||||
@ -12,6 +12,7 @@ import { InitiateKycRequestDto } from '../dtos/request';
|
|||||||
import { Customer } from '../entities';
|
import { Customer } from '../entities';
|
||||||
import { Gender, KycStatus } from '../enums';
|
import { Gender, KycStatus } from '../enums';
|
||||||
import { CustomerRepository } from '../repositories/customer.repository';
|
import { CustomerRepository } from '../repositories/customer.repository';
|
||||||
|
import { MetadataService } from './metadata.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CustomerService {
|
export class CustomerService {
|
||||||
@ -20,6 +21,7 @@ export class CustomerService {
|
|||||||
private readonly customerRepository: CustomerRepository,
|
private readonly customerRepository: CustomerRepository,
|
||||||
private readonly guardianService: GuardianService,
|
private readonly guardianService: GuardianService,
|
||||||
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
@Inject(forwardRef(() => NeoLeapService)) private readonly neoleapService: NeoLeapService,
|
||||||
|
private readonly metadataService: MetadataService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async updateCustomer(userId: string, data: Partial<Customer>): Promise<Customer> {
|
async updateCustomer(userId: string, data: Partial<Customer>): Promise<Customer> {
|
||||||
@ -149,6 +151,11 @@ export class CustomerService {
|
|||||||
return this.findCustomerById(userId);
|
return this.findCustomerById(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getKycOnboardMetadata() {
|
||||||
|
this.logger.log('Getting KYC onboard metadata');
|
||||||
|
return this.metadataService.getKycOnboardMetadata();
|
||||||
|
}
|
||||||
|
|
||||||
// TO BE REMOVED: This function is for testing only and will be removed
|
// TO BE REMOVED: This function is for testing only and will be removed
|
||||||
private generateSaudiPhoneNumber(): string {
|
private generateSaudiPhoneNumber(): string {
|
||||||
// Saudi mobile numbers are 9 digits, always starting with '5'
|
// Saudi mobile numbers are 9 digits, always starting with '5'
|
||||||
|
|||||||
@ -1 +1,2 @@
|
|||||||
export * from './customer.service';
|
export * from './customer.service';
|
||||||
|
export * from './metadata.service';
|
||||||
|
|||||||
105
src/customer/services/metadata.service.ts
Normal file
105
src/customer/services/metadata.service.ts
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { IncomeRange, IncomeSource, JobCategory, JobSector, PoiType } from '../enums';
|
||||||
|
import { KycMetadataResponseDto, MetadataOptionDto } from '../dtos/response';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MetadataService {
|
||||||
|
getKycOnboardMetadata(): KycMetadataResponseDto {
|
||||||
|
return {
|
||||||
|
poiTypes: this.enumToOptions(PoiType, {
|
||||||
|
[PoiType.IQA]: 'Iqama (Resident ID)',
|
||||||
|
[PoiType.NAT]: 'National ID',
|
||||||
|
}),
|
||||||
|
jobSectors: this.enumToOptions(JobSector, {
|
||||||
|
[JobSector.GOVERNMENT_SECTOR]: 'Government Sector',
|
||||||
|
[JobSector.HOME_MAKER]: 'Home Maker',
|
||||||
|
[JobSector.MILITARY]: 'Military',
|
||||||
|
[JobSector.PRIVATE_SECTOR]: 'Private Sector',
|
||||||
|
[JobSector.RETIRED]: 'Retired',
|
||||||
|
[JobSector.SELF_EMPLOYED]: 'Self Employed',
|
||||||
|
[JobSector.STUDENT]: 'Student',
|
||||||
|
[JobSector.HOUSEHOLD_LABOR]: 'Household Labor',
|
||||||
|
[JobSector.UNEMPLOYED]: 'Unemployed',
|
||||||
|
}),
|
||||||
|
incomeSources: this.enumToOptions(IncomeSource, {
|
||||||
|
[IncomeSource.SALARY]: 'Salary',
|
||||||
|
[IncomeSource.ANCESTRAL]: 'Ancestral/Inheritance',
|
||||||
|
[IncomeSource.REAL_ESTATE]: 'Real Estate',
|
||||||
|
[IncomeSource.INVESTMENT_RETURNS]: 'Investment Returns',
|
||||||
|
[IncomeSource.RENTAL_INCOME]: 'Rental Income',
|
||||||
|
[IncomeSource.OTHER]: 'Other',
|
||||||
|
}),
|
||||||
|
jobCategories: this.enumToOptions(JobCategory, {
|
||||||
|
[JobCategory.ASSISTANT_MINISTER]: 'Assistant Minister',
|
||||||
|
[JobCategory.DEPUTY_MINISTER]: 'Deputy Minister',
|
||||||
|
[JobCategory.UNDER_SECRETARY]: 'Under Secretary',
|
||||||
|
[JobCategory.GENERAL_MANAGER]: 'General Manager',
|
||||||
|
[JobCategory.CHAIRMAN]: 'Chairman',
|
||||||
|
[JobCategory.MANAGER]: 'Manager',
|
||||||
|
[JobCategory.PROFESSOR]: 'Professor',
|
||||||
|
[JobCategory.HEAD_OF_COURT]: 'Head of Court',
|
||||||
|
[JobCategory.JUDGE]: 'Judge',
|
||||||
|
[JobCategory.LAWYER]: 'Lawyer',
|
||||||
|
[JobCategory.SCIENTIST]: 'Scientist',
|
||||||
|
[JobCategory.NOTARY]: 'Notary',
|
||||||
|
[JobCategory.BUSINESSMAN]: 'Businessman',
|
||||||
|
[JobCategory.MERCHANT]: 'Merchant',
|
||||||
|
[JobCategory.PHARMACIST]: 'Pharmacist',
|
||||||
|
[JobCategory.DOCTOR]: 'Doctor',
|
||||||
|
[JobCategory.MEDICAL_TECHNICIAN]: 'Medical Technician',
|
||||||
|
[JobCategory.NURSE]: 'Nurse',
|
||||||
|
[JobCategory.ENGINEER]: 'Engineer',
|
||||||
|
[JobCategory.CHEMIST]: 'Chemist',
|
||||||
|
[JobCategory.CONTRACTOR]: 'Contractor',
|
||||||
|
[JobCategory.AUDITOR_ACCOUNTANT]: 'Auditor/Accountant',
|
||||||
|
[JobCategory.RESEARCHER]: 'Researcher',
|
||||||
|
[JobCategory.ACCOUNTANT]: 'Accountant',
|
||||||
|
[JobCategory.JOURNALIST]: 'Journalist',
|
||||||
|
[JobCategory.DESIGNER]: 'Designer',
|
||||||
|
[JobCategory.COMPUTER_SPECIALIST]: 'Computer Specialist',
|
||||||
|
[JobCategory.TRANSLATOR]: 'Translator',
|
||||||
|
[JobCategory.TEACHER]: 'Teacher',
|
||||||
|
[JobCategory.PILOT]: 'Pilot',
|
||||||
|
[JobCategory.HOST]: 'Host',
|
||||||
|
[JobCategory.OFFICER]: 'Officer',
|
||||||
|
[JobCategory.SOLDIER]: 'Soldier',
|
||||||
|
[JobCategory.RETIRED]: 'Retired',
|
||||||
|
[JobCategory.SALESMAN]: 'Salesman',
|
||||||
|
[JobCategory.AUTHOR]: 'Author',
|
||||||
|
[JobCategory.CRAFTSMAN]: 'Craftsman',
|
||||||
|
[JobCategory.SECURITY]: 'Security',
|
||||||
|
[JobCategory.LABORER]: 'Laborer',
|
||||||
|
[JobCategory.DRIVER]: 'Driver',
|
||||||
|
[JobCategory.FARMER]: 'Farmer',
|
||||||
|
[JobCategory.HOUSEWIFE]: 'Housewife',
|
||||||
|
[JobCategory.DIPLOMAT]: 'Diplomat',
|
||||||
|
[JobCategory.STUDENT]: 'Student',
|
||||||
|
[JobCategory.FREELANCER]: 'Freelancer',
|
||||||
|
[JobCategory.SHEPHERD]: 'Shepherd',
|
||||||
|
[JobCategory.HOUSEMAID_OR_BABYSITTER]: 'Housemaid/Babysitter',
|
||||||
|
[JobCategory.CAPTAIN]: 'Captain',
|
||||||
|
[JobCategory.AMBASSADOR]: 'Ambassador',
|
||||||
|
[JobCategory.MARKETING]: 'Marketing',
|
||||||
|
[JobCategory.CONSULTING]: 'Consulting',
|
||||||
|
[JobCategory.SUPERVISOR]: 'Supervisor',
|
||||||
|
[JobCategory.BANKER]: 'Banker',
|
||||||
|
[JobCategory.BODYGUARD_OR_PERSONAL_ASSISTANT]: 'Bodyguard/Personal Assistant',
|
||||||
|
}),
|
||||||
|
incomeRanges: this.enumToOptions(IncomeRange, {
|
||||||
|
[IncomeRange.BELOW_2000]: 'SAR 2,000 and below',
|
||||||
|
[IncomeRange.RANGE_2000_5000]: 'SAR 2,000 to 5,000',
|
||||||
|
[IncomeRange.RANGE_5000_10000]: 'SAR 5,000 to 10,000',
|
||||||
|
[IncomeRange.RANGE_10000_20000]: 'SAR 10,000 to 20,000',
|
||||||
|
[IncomeRange.ABOVE_20000]: 'SAR 20,000 and above',
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private enumToOptions(enumObj: any, labels: Record<string, string>): MetadataOptionDto[] {
|
||||||
|
return Object.keys(enumObj).map((key) => ({
|
||||||
|
value: enumObj[key],
|
||||||
|
label: labels[enumObj[key]] || enumObj[key],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
65
src/customer/validators/poi-number.validator.ts
Normal file
65
src/customer/validators/poi-number.validator.ts
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import {
|
||||||
|
registerDecorator,
|
||||||
|
ValidationOptions,
|
||||||
|
ValidatorConstraint,
|
||||||
|
ValidatorConstraintInterface,
|
||||||
|
ValidationArguments,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { PoiType } from '../enums';
|
||||||
|
|
||||||
|
@ValidatorConstraint({ name: 'IsValidPoiNumber', async: false })
|
||||||
|
export class IsValidPoiNumberConstraint implements ValidatorConstraintInterface {
|
||||||
|
validate(poiNumber: string, args: ValidationArguments) {
|
||||||
|
const object = args.object as any;
|
||||||
|
const poiType = object.poiType;
|
||||||
|
|
||||||
|
if (!poiNumber || !poiType) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Saudi National ID: 10 digits, typically starts with 1 or 2
|
||||||
|
const nationalIdPattern = /^[12]\d{9}$/;
|
||||||
|
|
||||||
|
// Iqama (Resident ID): 10 digits, typically starts with other numbers (not 1 or 2)
|
||||||
|
const iqamaPattern = /^[3-9]\d{9}$/;
|
||||||
|
|
||||||
|
if (poiType === PoiType.NAT) {
|
||||||
|
return nationalIdPattern.test(poiNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (poiType === PoiType.IQA) {
|
||||||
|
return iqamaPattern.test(poiNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultMessage(args: ValidationArguments) {
|
||||||
|
const object = args.object as any;
|
||||||
|
const poiType = object.poiType;
|
||||||
|
|
||||||
|
if (poiType === PoiType.NAT) {
|
||||||
|
return 'National ID must be 10 digits and start with 1 or 2';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (poiType === PoiType.IQA) {
|
||||||
|
return 'Iqama number must be 10 digits and start with 3-9';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Invalid POI number format';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IsValidPoiNumber(validationOptions?: ValidationOptions) {
|
||||||
|
return function (object: Object, propertyName: string) {
|
||||||
|
registerDecorator({
|
||||||
|
target: object.constructor,
|
||||||
|
propertyName: propertyName,
|
||||||
|
options: validationOptions,
|
||||||
|
constraints: [],
|
||||||
|
validator: IsValidPoiNumberConstraint,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -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"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -3,3 +3,6 @@ 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 './1757349525708-create-money-requests-table';
|
||||||
export * from './1757433339849-add-reservation-amount-to-account-entity';
|
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';
|
||||||
|
|
||||||
|
|
||||||
@ -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'
|
||||||
|
|||||||
@ -19,6 +19,10 @@
|
|||||||
"TOKEN_EXPIRED": "رمز المستخدم منتهي الصلاحية."
|
"TOKEN_EXPIRED": "رمز المستخدم منتهي الصلاحية."
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"QR": {
|
||||||
|
"CODE_USED_OR_EXPIRED": "تم استخدام رمز QR مسبقًا أو انتهت صلاحيته."
|
||||||
|
},
|
||||||
|
|
||||||
"USER": {
|
"USER": {
|
||||||
"PHONE_ALREADY_VERIFIED": "تم التحقق من رقم الهاتف بالفعل.",
|
"PHONE_ALREADY_VERIFIED": "تم التحقق من رقم الهاتف بالفعل.",
|
||||||
"EMAIL_ALREADY_VERIFIED": "تم التحقق من عنوان البريد الإلكتروني بالفعل.",
|
"EMAIL_ALREADY_VERIFIED": "تم التحقق من عنوان البريد الإلكتروني بالفعل.",
|
||||||
@ -68,7 +72,8 @@
|
|||||||
"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_UPDATE_REGISTERED_USER": "الطفل قد سجل بالفعل. لا يُسمح بتحديث البيانات.",
|
||||||
|
"CANNOT_DELETE_REGISTERED_USER": "الطفل قد سجل بالفعل. لا يُسمح بحذف الطفل."
|
||||||
},
|
},
|
||||||
|
|
||||||
"MONEY_REQUEST": {
|
"MONEY_REQUEST": {
|
||||||
@ -103,6 +108,7 @@
|
|||||||
},
|
},
|
||||||
"CARD": {
|
"CARD": {
|
||||||
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
|
"INSUFFICIENT_BALANCE": "البطاقة لا تحتوي على رصيد كافٍ لإكمال هذا التحويل.",
|
||||||
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر."
|
"DOES_NOT_BELONG_TO_GUARDIAN": "البطاقة لا تنتمي إلى ولي الأمر.",
|
||||||
|
"NOT_FOUND": "لم يتم العثور على البطاقة."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,6 +19,10 @@
|
|||||||
"TOKEN_EXPIRED": "The user token has expired."
|
"TOKEN_EXPIRED": "The user token has expired."
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"QR": {
|
||||||
|
"CODE_USED_OR_EXPIRED": "The QR code has already been used or expired."
|
||||||
|
},
|
||||||
|
|
||||||
"USER": {
|
"USER": {
|
||||||
"PHONE_ALREADY_VERIFIED": "The phone number has already been verified.",
|
"PHONE_ALREADY_VERIFIED": "The phone number has already been verified.",
|
||||||
"EMAIL_ALREADY_VERIFIED": "The email address has already been verified.",
|
"EMAIL_ALREADY_VERIFIED": "The email address has already been verified.",
|
||||||
@ -67,7 +71,8 @@
|
|||||||
"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_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": {
|
||||||
@ -102,6 +107,7 @@
|
|||||||
},
|
},
|
||||||
"CARD": {
|
"CARD": {
|
||||||
"INSUFFICIENT_BALANCE": "The card does not have sufficient balance to complete this transfer.",
|
"INSUFFICIENT_BALANCE": "The card does not have sufficient balance to complete this transfer.",
|
||||||
"DOES_NOT_BELONG_TO_GUARDIAN": "The card does not belong to the guardian."
|
"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, Patch, 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';
|
||||||
@ -20,6 +32,8 @@ import {
|
|||||||
ThemeResponseDto,
|
ThemeResponseDto,
|
||||||
TransferToJuniorResponseDto,
|
TransferToJuniorResponseDto,
|
||||||
} from '../dtos/response';
|
} 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')
|
||||||
@ -83,6 +97,14 @@ export class JuniorController {
|
|||||||
return ResponseFactory.data(new JuniorResponseDto(junior));
|
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)
|
||||||
@ -124,4 +146,82 @@ export class JuniorController {
|
|||||||
|
|
||||||
return ResponseFactory.data(new TransferToJuniorResponseDto(newAmount));
|
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,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];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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,6 +2,7 @@ import {
|
|||||||
BaseEntity,
|
BaseEntity,
|
||||||
Column,
|
Column,
|
||||||
CreateDateColumn,
|
CreateDateColumn,
|
||||||
|
DeleteDateColumn,
|
||||||
Entity,
|
Entity,
|
||||||
JoinColumn,
|
JoinColumn,
|
||||||
ManyToOne,
|
ManyToOne,
|
||||||
@ -49,4 +50,7 @@ export class Junior extends BaseEntity {
|
|||||||
|
|
||||||
@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';
|
||||||
|
|||||||
@ -65,4 +65,8 @@ export class JuniorRepository {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
softDelete(juniorId: string) {
|
||||||
|
return this.juniorRepository.softDelete({ id: juniorId });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,11 @@
|
|||||||
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 { ErrorCategory } from '~/core/enums';
|
||||||
import { setIf } from '~/core/utils';
|
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';
|
||||||
@ -19,6 +21,7 @@ import {
|
|||||||
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 {
|
||||||
@ -33,6 +36,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()
|
||||||
@ -110,18 +114,40 @@ export class JuniorService {
|
|||||||
}
|
}
|
||||||
junior.customer.user.email = body.email;
|
junior.customer.user.email = body.email;
|
||||||
}
|
}
|
||||||
setIf(user, 'profilePictureId', body.profilePictureId);
|
// Update profile picture: ensure FK and relation are consistent to avoid TypeORM overriding the FK
|
||||||
|
if (typeof body.profilePictureId !== 'undefined') {
|
||||||
|
if (body.profilePictureId) {
|
||||||
|
const document = await this.documentService.findDocumentById(body.profilePictureId);
|
||||||
|
if (!document) {
|
||||||
|
this.logger.error(`Document with id ${body.profilePictureId} not found`);
|
||||||
|
throw new BadRequestException('DOCUMENT.NOT_FOUND');
|
||||||
|
}
|
||||||
|
if (document.createdById !== juniorId) {
|
||||||
|
this.logger.error(
|
||||||
|
`Document with id ${body.profilePictureId} does not belong to user ${juniorId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
user.profilePictureId = body.profilePictureId;
|
||||||
|
// assign relation to keep it consistent with FK during save
|
||||||
|
user.profilePicture = document as any;
|
||||||
|
} else {
|
||||||
|
// if empty string provided (unlikely), clear relation and FK
|
||||||
|
user.profilePicture = null as any;
|
||||||
|
user.profilePictureId = null as any;
|
||||||
|
}
|
||||||
|
}
|
||||||
setIf(user, 'firstName', body.firstName);
|
setIf(user, 'firstName', body.firstName);
|
||||||
setIf(user, 'lastName', body.lastName);
|
setIf(user, 'lastName', body.lastName);
|
||||||
|
|
||||||
setIf(customer, 'firstName', body.firstName);
|
setIf(customer, 'firstName', body.firstName);
|
||||||
setIf(customer, 'lastName', body.lastName);
|
setIf(customer, 'lastName', body.lastName);
|
||||||
setIf(customer, 'dateOfBirth', body.dateOfBirth as unknown as Date);
|
setIf(customer, 'dateOfBirth', body.dateOfBirth as unknown as Date);
|
||||||
|
setIf(customer, 'gender', body.gender);
|
||||||
|
|
||||||
setIf(junior, 'relationship', body.relationship);
|
setIf(junior, 'relationship', body.relationship);
|
||||||
await Promise.all([junior.save(), customer.save(), user.save()]);
|
await Promise.all([junior.save(), customer.save(), user.save()]);
|
||||||
this.logger.log(`Junior ${juniorId} updated successfully`);
|
this.logger.log(`Junior ${juniorId} updated successfully`);
|
||||||
return junior;
|
return this.findJuniorById(juniorId, false, guardianId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional()
|
@Transactional()
|
||||||
@ -154,7 +180,14 @@ export class JuniorService {
|
|||||||
async validateToken(token: string) {
|
async validateToken(token: string) {
|
||||||
this.logger.log(`Validating token ${token}`);
|
this.logger.log(`Validating token ${token}`);
|
||||||
const juniorId = await this.userTokenService.validateToken(token, UserType.JUNIOR);
|
const juniorId = await this.userTokenService.validateToken(token, UserType.JUNIOR);
|
||||||
return this.findJuniorById(juniorId!, true);
|
const junior = await this.findJuniorById(juniorId!, true);
|
||||||
|
|
||||||
|
if (junior.customer?.user?.password) {
|
||||||
|
this.logger.error(`Token ${token} already used for junior ${juniorId}`);
|
||||||
|
throw new BadRequestException({ message: 'QR.CODE_USED_OR_EXPIRED', category: ErrorCategory.BUSINESS_ERROR });
|
||||||
|
}
|
||||||
|
|
||||||
|
return junior;
|
||||||
}
|
}
|
||||||
|
|
||||||
async generateToken(juniorId: string) {
|
async generateToken(juniorId: string) {
|
||||||
@ -183,6 +216,129 @@ export class JuniorService {
|
|||||||
return this.cardService.transferToChild(juniorId, body.amount);
|
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,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,20 +191,50 @@ 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) {
|
||||||
return;
|
this.logger.log(`Generating OTP for current email ${email} for user ${userId}`);
|
||||||
|
await this.userRepository.update(userId, { isEmailVerified: false });
|
||||||
|
|
||||||
|
return this.otpService.generateAndSendOtp({
|
||||||
|
userId,
|
||||||
|
recipient: email,
|
||||||
|
otpType: OtpType.EMAIL,
|
||||||
|
scope: OtpScope.VERIFY_EMAIL,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logger.error(`Email ${email} is already taken by another user`);
|
this.logger.error(`Email ${email} is already taken by another user`);
|
||||||
|
|||||||
Reference in New Issue
Block a user