refactor(api): replace new Logger() with DI LoggerService and split large files

- Migrate 30 files from `new Logger(ClassName.name)` to injected LoggerService
  for consistent PII masking and centralized logging config
- Split prisma-admin-query.repository.ts (313→121 lines) into admin-stats.queries.ts
  and admin-user.queries.ts
- Split admin.controller.ts (285→154 lines) into admin-moderation.controller.ts
- Split prisma-listing.repository.ts (274→111 lines) into listing-read.queries.ts
- Update 28 test files with mock LoggerService
- All 831 tests passing, zero direct new Logger() calls remaining

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-10 05:35:04 +07:00
parent 4e71036ddd
commit 34202f2527
67 changed files with 851 additions and 653 deletions

View File

@@ -35,10 +35,13 @@ describe('CreatePaymentHandler', () => {
mockEventBus = { publish: vi.fn() };
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
handler = new CreatePaymentHandler(
mockPaymentRepo as any,
mockGatewayFactory as any,
mockEventBus as any,
mockLogger as any,
);
});

View File

@@ -48,10 +48,13 @@ describe('HandleCallbackHandler — edge cases', () => {
mockGatewayFactory = { getGateway: vi.fn().mockReturnValue(mockGateway) };
mockEventBus = { publish: vi.fn() };
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
handler = new HandleCallbackHandler(
mockPaymentRepo as any,
mockGatewayFactory as any,
mockEventBus as any,
mockLogger as any,
);
});

View File

@@ -43,10 +43,13 @@ describe('HandleCallbackHandler', () => {
mockGatewayFactory = { getGateway: vi.fn().mockReturnValue(mockGateway) };
mockEventBus = { publish: vi.fn() };
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
handler = new HandleCallbackHandler(
mockPaymentRepo as any,
mockGatewayFactory as any,
mockEventBus as any,
mockLogger as any,
);
});

View File

@@ -38,9 +38,12 @@ describe('RefundPaymentHandler', () => {
mockGatewayFactory = { getGateway: vi.fn().mockReturnValue(mockGateway) };
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
handler = new RefundPaymentHandler(
mockPaymentRepo as any,
mockGatewayFactory as any,
mockLogger as any,
);
});

View File

@@ -1,7 +1,7 @@
import { Inject, Logger } from '@nestjs/common';
import { Inject } from '@nestjs/common';
import { CommandHandler, type EventBus, type ICommandHandler } from '@nestjs/cqrs';
import { createId } from '@paralleldrive/cuid2';
import { ConflictException, ValidationException } from '@modules/shared';
import { ConflictException, ValidationException, type LoggerService } from '@modules/shared';
import { PaymentEntity } from '../../../domain/entities/payment.entity';
import {
PAYMENT_REPOSITORY,
@@ -22,14 +22,13 @@ export interface CreatePaymentResult {
@CommandHandler(CreatePaymentCommand)
export class CreatePaymentHandler implements ICommandHandler<CreatePaymentCommand> {
private readonly logger = new Logger(CreatePaymentHandler.name);
constructor(
@Inject(PAYMENT_REPOSITORY)
private readonly paymentRepo: IPaymentRepository,
@Inject(PAYMENT_GATEWAY_FACTORY)
private readonly gatewayFactory: IPaymentGatewayFactory,
private readonly eventBus: EventBus,
private readonly logger: LoggerService,
) {}
async execute(command: CreatePaymentCommand): Promise<CreatePaymentResult> {
@@ -86,6 +85,7 @@ export class CreatePaymentHandler implements ICommandHandler<CreatePaymentComman
this.logger.log(
`Payment created: id=${paymentId}, provider=${command.provider}, amount=${command.amountVND}`,
'CreatePaymentHandler',
);
return { paymentId, paymentUrl, providerTxId };

View File

@@ -1,7 +1,7 @@
import { Inject, Logger } from '@nestjs/common';
import { Inject } from '@nestjs/common';
import { CommandHandler, type EventBus, type ICommandHandler } from '@nestjs/cqrs';
import { type PaymentStatus } from '@prisma/client';
import { NotFoundException, ValidationException } from '@modules/shared';
import { NotFoundException, ValidationException, type LoggerService } from '@modules/shared';
import {
PAYMENT_REPOSITORY,
type IPaymentRepository,
@@ -20,14 +20,13 @@ export interface HandleCallbackResult {
@CommandHandler(HandleCallbackCommand)
export class HandleCallbackHandler implements ICommandHandler<HandleCallbackCommand> {
private readonly logger = new Logger(HandleCallbackHandler.name);
constructor(
@Inject(PAYMENT_REPOSITORY)
private readonly paymentRepo: IPaymentRepository,
@Inject(PAYMENT_GATEWAY_FACTORY)
private readonly gatewayFactory: IPaymentGatewayFactory,
private readonly eventBus: EventBus,
private readonly logger: LoggerService,
) {}
async execute(command: HandleCallbackCommand): Promise<HandleCallbackResult> {
@@ -37,6 +36,7 @@ export class HandleCallbackHandler implements ICommandHandler<HandleCallbackComm
if (!result.isValid) {
this.logger.warn(
`Invalid callback signature for provider=${command.provider}`,
'HandleCallbackHandler',
);
throw new ValidationException('Chữ ký callback không hợp lệ');
}
@@ -57,13 +57,14 @@ export class HandleCallbackHandler implements ICommandHandler<HandleCallbackComm
// Either payment doesn't exist or is already in a terminal state
const existing = await this.paymentRepo.findById(result.orderId);
if (!existing) {
this.logger.warn(`Payment not found for orderId=${result.orderId}`);
this.logger.warn(`Payment not found for orderId=${result.orderId}`, 'HandleCallbackHandler');
throw new NotFoundException('Payment', result.orderId);
}
// Already processed — return idempotent response
this.logger.log(
`Payment ${existing.id} already in terminal state: ${existing.status}`,
'HandleCallbackHandler',
);
return {
paymentId: existing.id,
@@ -86,6 +87,7 @@ export class HandleCallbackHandler implements ICommandHandler<HandleCallbackComm
this.logger.log(
`Payment ${updated.id} callback processed: status=${updated.status}`,
'HandleCallbackHandler',
);
return {

View File

@@ -1,6 +1,6 @@
import { Inject, Logger } from '@nestjs/common';
import { Inject } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { NotFoundException, ValidationException } from '@modules/shared';
import { NotFoundException, ValidationException, type LoggerService } from '@modules/shared';
import {
PAYMENT_REPOSITORY,
type IPaymentRepository,
@@ -19,13 +19,12 @@ export interface RefundPaymentResult {
@CommandHandler(RefundPaymentCommand)
export class RefundPaymentHandler implements ICommandHandler<RefundPaymentCommand> {
private readonly logger = new Logger(RefundPaymentHandler.name);
constructor(
@Inject(PAYMENT_REPOSITORY)
private readonly paymentRepo: IPaymentRepository,
@Inject(PAYMENT_GATEWAY_FACTORY)
private readonly gatewayFactory: IPaymentGatewayFactory,
private readonly logger: LoggerService,
) {}
async execute(command: RefundPaymentCommand): Promise<RefundPaymentResult> {
@@ -59,6 +58,7 @@ export class RefundPaymentHandler implements ICommandHandler<RefundPaymentComman
this.logger.log(
`Refund ${result.success ? 'successful' : 'failed'} for payment ${command.paymentId}`,
'RefundPaymentHandler',
);
return {

View File

@@ -29,7 +29,8 @@ describe('MomoService', () => {
return env[key];
}),
} as unknown as ConfigService;
service = new MomoService(mockConfig);
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
service = new MomoService(mockConfig, mockLogger as any);
});
function buildCallbackData(overrides: Record<string, string> = {}): Record<string, string> {

View File

@@ -24,7 +24,8 @@ describe('VnpayService', () => {
return env[key];
}),
} as unknown as ConfigService;
service = new VnpayService(mockConfig);
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
service = new VnpayService(mockConfig, mockLogger as any);
});
it('should create a payment URL', async () => {

View File

@@ -27,7 +27,8 @@ describe('ZalopayService', () => {
return env[key];
}),
} as unknown as ConfigService;
service = new ZalopayService(mockConfig);
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
service = new ZalopayService(mockConfig, mockLogger as any);
});
function buildCallbackData(

View File

@@ -1,7 +1,8 @@
import * as crypto from 'crypto';
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { type ConfigService } from '@nestjs/config';
import { type PaymentProvider } from '@prisma/client';
import { type LoggerService } from '@modules/shared';
import {
type IPaymentGateway,
type CreatePaymentUrlParams,
@@ -13,7 +14,6 @@ import {
@Injectable()
export class MomoService implements IPaymentGateway {
private readonly logger = new Logger(MomoService.name);
readonly provider: PaymentProvider = 'MOMO';
private readonly partnerCode: string;
@@ -21,7 +21,10 @@ export class MomoService implements IPaymentGateway {
private readonly secretKey: string;
private readonly endpoint: string;
constructor(private readonly config: ConfigService) {
constructor(
private readonly config: ConfigService,
private readonly logger: LoggerService,
) {
this.partnerCode = this.config.getOrThrow<string>('MOMO_PARTNER_CODE');
this.accessKey = this.config.getOrThrow<string>('MOMO_ACCESS_KEY');
this.secretKey = this.config.getOrThrow<string>('MOMO_SECRET_KEY');
@@ -84,14 +87,14 @@ export class MomoService implements IPaymentGateway {
throw new Error(`MoMo create payment failed: resultCode=${result.resultCode}`);
}
this.logger.log(`MoMo payment URL created for order ${params.orderId}`);
this.logger.log(`MoMo payment URL created for order ${params.orderId}`, 'MomoService');
return {
paymentUrl: result.payUrl,
providerTxId: params.orderId,
};
} catch (error) {
this.logger.error(`MoMo createPaymentUrl error: ${error}`);
this.logger.error(`MoMo createPaymentUrl error: ${error}`, undefined, 'MomoService');
throw error;
}
}
@@ -131,6 +134,7 @@ export class MomoService implements IPaymentGateway {
this.logger.log(
`MoMo callback verified: orderId=${orderId}, valid=${isValid}, success=${isSuccess}`,
'MomoService',
);
return {
@@ -184,6 +188,7 @@ export class MomoService implements IPaymentGateway {
this.logger.log(
`MoMo refund ${success ? 'successful' : 'failed'} for ${params.providerTxId}`,
'MomoService',
);
return {
@@ -191,7 +196,7 @@ export class MomoService implements IPaymentGateway {
refundTxId: success ? requestId : null,
};
} catch (error) {
this.logger.error(`MoMo refund error: ${error}`);
this.logger.error(`MoMo refund error: ${error}`, undefined, 'MomoService');
return { success: false, refundTxId: null };
}
}

View File

@@ -1,7 +1,8 @@
import * as crypto from 'crypto';
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { type ConfigService } from '@nestjs/config';
import { type PaymentProvider } from '@prisma/client';
import { type LoggerService } from '@modules/shared';
import {
type IPaymentGateway,
type CreatePaymentUrlParams,
@@ -13,7 +14,6 @@ import {
@Injectable()
export class VnpayService implements IPaymentGateway {
private readonly logger = new Logger(VnpayService.name);
readonly provider: PaymentProvider = 'VNPAY';
private readonly tmnCode: string;
@@ -21,7 +21,10 @@ export class VnpayService implements IPaymentGateway {
private readonly baseUrl: string;
private readonly apiUrl: string;
constructor(private readonly config: ConfigService) {
constructor(
private readonly config: ConfigService,
private readonly logger: LoggerService,
) {
this.tmnCode = this.config.getOrThrow<string>('VNPAY_TMN_CODE');
this.hashSecret = this.config.getOrThrow<string>('VNPAY_HASH_SECRET');
this.baseUrl = this.config.get<string>('VNPAY_BASE_URL', 'https://sandbox.vnpayment.vn/paymentv2/vpcpay.html');
@@ -58,7 +61,7 @@ export class VnpayService implements IPaymentGateway {
const paymentUrl = `${this.baseUrl}?${new URLSearchParams(sortedParams).toString()}`;
this.logger.log(`VNPay payment URL created for order ${params.orderId}`);
this.logger.log(`VNPay payment URL created for order ${params.orderId}`, 'VnpayService');
return {
paymentUrl,
@@ -89,6 +92,7 @@ export class VnpayService implements IPaymentGateway {
this.logger.log(
`VNPay callback verified: orderId=${orderId}, valid=${isValid}, success=${isSuccess}`,
'VnpayService',
);
return {
@@ -151,6 +155,7 @@ export class VnpayService implements IPaymentGateway {
this.logger.log(
`VNPay refund ${success ? 'successful' : 'failed'} for ${params.providerTxId}`,
'VnpayService',
);
return {
@@ -158,7 +163,7 @@ export class VnpayService implements IPaymentGateway {
refundTxId: success ? requestId : null,
};
} catch (error) {
this.logger.error(`VNPay refund error: ${error}`);
this.logger.error(`VNPay refund error: ${error}`, undefined, 'VnpayService');
return { success: false, refundTxId: null };
}
}

View File

@@ -1,7 +1,8 @@
import * as crypto from 'crypto';
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { type ConfigService } from '@nestjs/config';
import { type PaymentProvider } from '@prisma/client';
import { type LoggerService } from '@modules/shared';
import {
type IPaymentGateway,
type CreatePaymentUrlParams,
@@ -13,7 +14,6 @@ import {
@Injectable()
export class ZalopayService implements IPaymentGateway {
private readonly logger = new Logger(ZalopayService.name);
readonly provider: PaymentProvider = 'ZALOPAY';
private readonly appId: string;
@@ -21,7 +21,10 @@ export class ZalopayService implements IPaymentGateway {
private readonly key2: string;
private readonly endpoint: string;
constructor(private readonly config: ConfigService) {
constructor(
private readonly config: ConfigService,
private readonly logger: LoggerService,
) {
this.appId = this.config.getOrThrow<string>('ZALOPAY_APP_ID');
this.key1 = this.config.getOrThrow<string>('ZALOPAY_KEY1');
this.key2 = this.config.getOrThrow<string>('ZALOPAY_KEY2');
@@ -80,14 +83,14 @@ export class ZalopayService implements IPaymentGateway {
throw new Error(`ZaloPay create payment failed: return_code=${result.return_code}`);
}
this.logger.log(`ZaloPay payment URL created for order ${params.orderId}`);
this.logger.log(`ZaloPay payment URL created for order ${params.orderId}`, 'ZalopayService');
return {
paymentUrl: result.order_url,
providerTxId: appTransId,
};
} catch (error) {
this.logger.error(`ZaloPay createPaymentUrl error: ${error}`);
this.logger.error(`ZaloPay createPaymentUrl error: ${error}`, undefined, 'ZalopayService');
throw error;
}
}
@@ -128,6 +131,7 @@ export class ZalopayService implements IPaymentGateway {
this.logger.log(
`ZaloPay callback verified: orderId=${orderId}, valid=${isValid}`,
'ZalopayService',
);
return {
@@ -179,6 +183,7 @@ export class ZalopayService implements IPaymentGateway {
this.logger.log(
`ZaloPay refund ${success ? 'successful' : 'failed'} for ${params.providerTxId}`,
'ZalopayService',
);
return {
@@ -186,7 +191,7 @@ export class ZalopayService implements IPaymentGateway {
refundTxId: success ? mRefundId : null,
};
} catch (error) {
this.logger.error(`ZaloPay refund error: ${error}`);
this.logger.error(`ZaloPay refund error: ${error}`, undefined, 'ZalopayService');
return { success: false, refundTxId: null };
}
}