Skip to content

PM-1155 - refactor code #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,23 @@ import { TopcoderMembersService } from 'src/shared/topcoder/members.service';
import { Role } from 'src/core/auth/auth.constants';
import { Roles, User } from 'src/core/auth/decorators';

import { AdminWinningService } from './adminWinning.service';
import { UserInfo } from 'src/dto/user.dto';
import { UserInfo } from 'src/dto/user.type';

import {
ResponseStatusType,
ResponseDto,
WinningAuditDto,
WinningRequestDto,
SearchWinningResult,
WinningUpdateRequestDto,
AuditPayoutDto,
} from 'src/dto/adminWinning.dto';

@ApiTags('AdminWinning')
import { AdminService } from './admin.service';
import { ResponseDto, ResponseStatusType } from 'src/dto/api-response.dto';
import { WinningAuditDto, AuditPayoutDto } from './dto/audit.dto';

import { WinningRequestDto, SearchWinningResult } from 'src/dto/winning.dto';
import { WinningsRepository } from '../repository/winnings.repo';
import { WinningUpdateRequestDto } from './dto/winnings.dto';

@ApiTags('AdminWinnings')
@Controller('/admin')
@ApiBearerAuth()
export class AdminWinningController {
export class AdminController {
constructor(
private readonly adminWinningService: AdminWinningService,
private readonly adminService: AdminService,
private readonly winningsRepo: WinningsRepository,
private readonly tcMembersService: TopcoderMembersService,
) {}

Expand All @@ -65,7 +63,7 @@ export class AdminWinningController {
async searchWinnings(
@Body() body: WinningRequestDto,
): Promise<ResponseDto<SearchWinningResult>> {
const result = await this.adminWinningService.searchWinnings(body);
const result = await this.winningsRepo.searchWinnings(body);
if (result.error) {
result.status = ResponseStatusType.ERROR;
}
Expand Down Expand Up @@ -94,7 +92,7 @@ export class AdminWinningController {
@Header('Content-Type', 'text/csv')
@Header('Content-Disposition', 'attachment; filename="winnings.csv"')
async exportWinnings(@Body() body: WinningRequestDto) {
const result = await this.adminWinningService.searchWinnings({
const result = await this.winningsRepo.searchWinnings({
...body,
limit: 999,
});
Expand Down Expand Up @@ -172,7 +170,7 @@ export class AdminWinningController {
);
}

const result = await this.adminWinningService.updateWinnings(body, user.id);
const result = await this.adminService.updateWinnings(body, user.id);
if (result.error) {
result.status = ResponseStatusType.ERROR;
}
Expand Down Expand Up @@ -201,7 +199,7 @@ export class AdminWinningController {
async getWinningAudit(
@Param('winningID') winningId: string,
): Promise<ResponseDto<WinningAuditDto[]>> {
const result = await this.adminWinningService.getWinningAudit(winningId);
const result = await this.adminService.getWinningAudit(winningId);
if (result.error) {
result.status = ResponseStatusType.ERROR;
}
Expand Down Expand Up @@ -231,8 +229,7 @@ export class AdminWinningController {
async getWinningAuditPayout(
@Param('winningID') winningId: string,
): Promise<ResponseDto<AuditPayoutDto[]>> {
const result =
await this.adminWinningService.getWinningAuditPayout(winningId);
const result = await this.adminService.getWinningAuditPayout(winningId);
if (result.error) {
result.status = ResponseStatusType.ERROR;
}
Expand Down
19 changes: 19 additions & 0 deletions src/api/admin/admin.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Module } from '@nestjs/common';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { TaxFormRepository } from '../repository/taxForm.repo';
import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
import { WinningsRepository } from '../repository/winnings.repo';
import { TopcoderModule } from 'src/shared/topcoder/topcoder.module';

@Module({
imports: [TopcoderModule],
controllers: [AdminController],
providers: [
AdminService,
TaxFormRepository,
PaymentMethodRepository,
WinningsRepository,
],
})
export class AdminModule {}
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,18 @@ import {
import { PrismaPromise } from '@prisma/client';
import { PrismaService } from 'src/shared/global/prisma.service';

import {
DateFilterType,
ResponseDto,
WinningAuditDto,
WinningRequestDto,
SearchWinningResult,
WinningUpdateRequestDto,
PaymentStatus,
AuditPayoutDto,
WinningsCategory,
} from 'src/dto/adminWinning.dto';
import { TaxFormRepository } from '../repository/taxForm.repo';
import { PaymentMethodRepository } from '../repository/paymentMethod.repo';

const ONE_DAY = 24 * 60 * 60 * 1000;
import { ResponseDto } from 'src/dto/api-response.dto';
import { PaymentStatus } from 'src/dto/payment.dto';
import { WinningAuditDto, AuditPayoutDto } from './dto/audit.dto';
import { WinningUpdateRequestDto } from './dto/winnings.dto';

/**
* The admin winning service.
*/
@Injectable()
export class AdminWinningService {
export class AdminService {
/**
* Constructs the admin winning service with the given dependencies.
* @param prisma the prisma service.
Expand All @@ -39,202 +30,6 @@ export class AdminWinningService {
private readonly paymentMethodRepo: PaymentMethodRepository,
) {}

/**
* Search winnings with parameters
* @param body the request body
* @returns the Promise with response result
*/
async searchWinnings(
body: WinningRequestDto,
): Promise<ResponseDto<SearchWinningResult>> {
const result = new ResponseDto<SearchWinningResult>();

try {
let winnerIds: string[] | undefined;
let externalIds: string[] | undefined;
if (body.winnerId) {
winnerIds = [body.winnerId];
} else if (body.winnerIds) {
winnerIds = [...body.winnerIds];
} else if (body.externalIds?.length > 0) {
externalIds = body.externalIds;
}

const queryWhere = this.getQueryByWinnerId(body, winnerIds, externalIds);
const orderBy = this.getOrderByWithWinnerId(
body,
!winnerIds && !!externalIds?.length,
);

const [winnings, count] = await this.prisma.$transaction([
this.prisma.winnings.findMany({
...queryWhere,
include: {
payment: {
where: {
installment_number: 1,
},
orderBy: [
{
created_at: 'desc',
},
],
},
origin: true,
},
orderBy,
skip: body.offset,
take: body.limit,
}),
this.prisma.winnings.count({ where: queryWhere.where }),
]);

result.data = {
winnings: winnings.map((item) => ({
id: item.winning_id,
type: item.type,
winnerId: item.winner_id,
origin: item.origin?.origin_name,
category: (item.category ?? '') as WinningsCategory,
title: item.title as string,
description: item.description as string,
externalId: item.external_id as string,
attributes: (item.attributes ?? {}) as object,
details: item.payment?.map((paymentItem) => ({
id: paymentItem.payment_id,
netAmount: Number(paymentItem.net_amount),
grossAmount: Number(paymentItem.gross_amount),
totalAmount: Number(paymentItem.total_amount),
installmentNumber: paymentItem.installment_number as number,
datePaid: (paymentItem.date_paid ?? undefined) as Date,
status: paymentItem.payment_status as PaymentStatus,
currency: paymentItem.currency as string,
releaseDate: paymentItem.release_date as Date,
category: item.category as string,
billingAccount: paymentItem.billing_account,
})),
createdAt: item.created_at as Date,
updatedAt: (item.payment?.[0].date_paid ??
item.payment?.[0].updated_at ??
undefined) as Date,
releaseDate: item.payment?.[0]?.release_date as Date,
})),
pagination: {
totalItems: count,
totalPages: Math.ceil(count / body.limit),
pageSize: body.limit,
currentPage: Math.ceil(body.offset / body.limit) + 1,
},
};
// response.data = winnings as any
} catch (error) {
console.error('Searching winnings failed', error);
const message = 'Searching winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
message,
};
}

return result;
}

private generateFilterDate(body: WinningRequestDto) {
let filterDate: object | undefined;
const currentDay = new Date(new Date().setHours(0, 0, 0, 0));
switch (body.date) {
case DateFilterType.LAST7DAYS:
// eslint-disable-next-line no-case-declarations
const last7days = new Date(currentDay.getTime() - 6 * ONE_DAY);
filterDate = {
gte: last7days,
};
break;
case DateFilterType.LAST30DAYS:
// eslint-disable-next-line no-case-declarations
const last30days = new Date(currentDay.getTime() - 29 * ONE_DAY);
filterDate = {
gte: last30days,
};
break;
case DateFilterType.ALL:
filterDate = undefined;
break;
default:
break;
}
return filterDate;
}

private getQueryByWinnerId(
body: WinningRequestDto,
winnerIds: string[] | undefined,
externalIds: string[] | undefined,
) {
const filterDate: object | undefined = this.generateFilterDate(body);

const query = {
where: {
winner_id: winnerIds
? {
in: winnerIds,
}
: undefined,
external_id: externalIds
? {
in: body.externalIds,
}
: undefined,
category: body.type
? {
equals: body.type,
}
: undefined,
created_at: filterDate,
payment: body.status
? {
some: {
payment_status: {
equals: body.status,
},
installment_number: {
equals: 1,
},
},
}
: {
some: {
installment_number: {
equals: 1,
},
},
},
},
};

return query;
}

private getOrderByWithWinnerId(
body: WinningRequestDto,
externalIds?: boolean,
) {
const orderBy: object = [
{
created_at: 'desc',
},
...(externalIds ? [{ external_id: 'asc' }] : []),
];

if (body.sortBy && body.sortOrder) {
orderBy[0] = {
[body.sortBy]: body.sortOrder.toString(),
};
}

return orderBy;
}

private getPaymentsByWinningsId(winningsId: string, paymentId?: string) {
return this.prisma.payment.findMany({
where: {
Expand Down
49 changes: 49 additions & 0 deletions src/api/admin/dto/audit.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { ApiProperty } from '@nestjs/swagger';

export class WinningAuditDto {
@ApiProperty({
description: 'The ID of the audit',
example: '2ccba36d-8db7-49da-94c9-b6c5b7bf47fb',
})
id: string;

@ApiProperty({
description: 'The ID of the winning',
example: '2ccba36d-8db7-49da-94c9-b6c5b7bf47fc',
})
winningsId: string;

@ApiProperty({
description: 'The ID of the user',
example: '123',
})
userId: string;

@ApiProperty({
description: 'The audit action',
example: 'create payment',
})
action: string;

@ApiProperty({
description: 'The audit note',
example: 'note 01',
})
note: string | null;

@ApiProperty({
description: 'The creation timestamp',
example: '2023-10-01T00:00:00Z',
})
createdAt: Date;
}

export class AuditPayoutDto {
externalTransactionId: string;
status: string;
totalNetAmount: number;
createdAt: Date;
metadata: string;
paymentMethodUsed: string;
externalTransactionDetails: object;
}
Loading
Loading