feat(payment): add Idempotency guard, Amount Match check, auto Inquiry reconciliation and comprehensive Admin Transaction Logs management
Deploy Canina / deploy (push) Successful in 2m16s

This commit is contained in:
parsa aghaei committed 2026-08-16 12:08:50 +03:30
1 parent 8de1351349
commit 5ace474d71
17 files changed
+12754 -9884

No files matched your search

@@ -0,0 +1,69 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString, IsNumber, IsIn } from 'class-validator';
import { Type } from 'class-transformer';
export class AdminTransactionFilterDto {
@ApiPropertyOptional({ description: 'شماره صفحه', default: 1 })
@IsOptional()
@Type(() => Number)
@IsNumber()
page?: number = 1;
@ApiPropertyOptional({ description: 'تعداد در هر صفحه', default: 15 })
@IsOptional()
@Type(() => Number)
@IsNumber()
limit?: number = 15;
@ApiPropertyOptional({ description: 'جستجو (نام، موبایل، کد پیگیری، شماره مرجع، کد رهگیری)' })
@IsOptional()
@IsString()
search?: string;
@ApiPropertyOptional({ description: 'فیلتر وضعیت (VERIFIED, PENDING, FAILED)' })
@IsOptional()
@IsString()
status?: string;
@ApiPropertyOptional({ description: 'فیلتر درگاه (zibal, wallet, card)' })
@IsOptional()
@IsString()
gateway?: string;
@ApiPropertyOptional({ description: 'فیلتر نوع تراکنش (ORDER, WALLET_TOPUP)' })
@IsOptional()
@IsString()
type?: string;
@ApiPropertyOptional({ description: 'از تاریخ (ISO format)' })
@IsOptional()
@IsString()
startDate?: string;
@ApiPropertyOptional({ description: 'تا تاریخ (ISO format)' })
@IsOptional()
@IsString()
endDate?: string;
@ApiPropertyOptional({ description: 'حداقل مبلغ (تومان)' })
@IsOptional()
@Type(() => Number)
@IsNumber()
minAmount?: number;
@ApiPropertyOptional({ description: 'حداکثر مبلغ (تومان)' })
@IsOptional()
@Type(() => Number)
@IsNumber()
maxAmount?: number;
@ApiPropertyOptional({ description: 'فیلد مرتب‌سازی', default: 'createdAt' })
@IsOptional()
@IsString()
sortBy?: string = 'createdAt';
@ApiPropertyOptional({ description: 'جهت مرتب‌سازی (asc, desc)', default: 'desc' })
@IsOptional()
@IsIn(['asc', 'desc'])
sortOrder?: 'asc' | 'desc' = 'desc';
}
+42 -9
View File
@@ -18,7 +18,10 @@ import {
InitiateWalletTopupDto,
} from './dto/initiate-payment.dto';
import { ZibalCallbackQueryDto } from './dto/verify-payment.dto';
import { AdminTransactionFilterDto } from './dto/admin-transaction-filter.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import {
ApiTags,
ApiOperation,
@@ -27,7 +30,7 @@ import {
ApiBadRequestResponse,
} from '@nestjs/swagger';
@ApiTags('Payment - درگاه پرداخت اینترنتی زیبال (Zibal IPG)')
@ApiTags('Payment - درگاه پرداخت اینترنتی زیبال و مدیریت تراکنش‌ها')
@Controller('payment')
export class PaymentController {
constructor(
@@ -71,14 +74,6 @@ export class PaymentController {
@ApiOperation({ summary: 'شارژ آنلاین کیف پول از طریق درگاه زیبال' })
@ApiOkResponse({
description: 'لینک هدایت به درگاه پرداخت برای شارژ کیف پول',
schema: {
example: {
success: true,
trackId: '15966442233311',
paymentUrl: 'https://gateway.zibal.ir/start/15966442233311',
amount: 500000,
},
},
})
async initiateWalletTopup(
@Req() req: { user: { id: string } },
@@ -173,4 +168,42 @@ export class PaymentController {
async getTransactionStatus(@Param('trackId') trackId: string) {
return this.paymentService.getTransaction(trackId);
}
// --- ADMIN ENDPOINTS FOR TRANSACTION LOGS & DIAGNOSTICS ---
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Get('admin/transactions')
@ApiOperation({ summary: 'مدیریت و مشاهده تمامی لاگ‌ها و تراکنش‌های پرداخت' })
async getAdminTransactions(@Query() query: AdminTransactionFilterDto) {
return this.paymentService.getAdminTransactions(query);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Get('admin/stats')
@ApiOperation({ summary: 'آمار کلی تراکنش‌ها و حجم مبالغ پرداختی' })
async getAdminStats() {
return this.paymentService.getAdminTransactionStats();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Post('admin/reconcile')
@ApiOperation({ summary: 'اجرای فرایند انطباق و استعلام خودکار تراکنش‌های بلاتکلیف' })
async reconcilePending() {
return this.paymentService.reconcilePendingTransactions();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Get('admin/live-inquiry/:id')
@ApiOperation({ summary: 'استعلام زنده وضعیت تراکنش از سرور زیبال' })
async liveInquiry(@Param('id') id: string) {
return this.paymentService.adminLiveInquiry(id);
}
}
+353 -27
View File
@@ -8,6 +8,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { ZibalService } from './zibal.service';
import { SmsService } from '../common/services/sms.service';
import { Prisma } from '@prisma/client';
import { AdminTransactionFilterDto } from './dto/admin-transaction-filter.dto';
@Injectable()
export class PaymentService {
@@ -36,10 +37,8 @@ export class PaymentService {
throw new NotFoundException('سفارش مورد نظر یافت نشد');
}
if (order.status !== 'processing' && order.status !== 'pending_payment') {
if (['shipped', 'delivered'].includes(order.status)) {
throw new BadRequestException('این سفارش قبلاً تکمیل و ارسال شده است');
}
if (['shipped', 'delivered'].includes(order.status)) {
throw new BadRequestException('این سفارش قبلاً تکمیل و ارسال شده است');
}
const amountTomans = Number(order.totalAmount);
@@ -52,7 +51,6 @@ export class PaymentService {
}
const frontendUrl = await this.zibalService.getFrontendUrl();
// Default callback points to frontend verify page (or backend proxy)
const callbackUrl =
customCallbackUrl || `${frontendUrl}/payment/verify?orderId=${order.id}`;
@@ -201,7 +199,7 @@ export class PaymentService {
}
/**
* 3. Verify & Process Callback from Zibal
* 3. Verify & Process Callback from Zibal (With Idempotency & Amount Match Check)
*/
async verifyAndProcess(
trackId: string,
@@ -217,37 +215,42 @@ export class PaymentService {
where: { trackId },
include: {
order: {
include: { user: true, orderItems: { include: { product: true } } },
include: {
user: true,
orderItems: { include: { product: true } },
},
},
user: true,
},
});
if (!transaction) {
// If transaction not found by trackId, check if orderId exists
if (orderIdParam) {
transaction = await this.prisma.paymentTransaction.findFirst({
where: { orderId: orderIdParam },
orderBy: { createdAt: 'desc' },
include: {
order: {
include: {
user: true,
orderItems: { include: { product: true } },
},
if (!transaction && orderIdParam) {
transaction = await this.prisma.paymentTransaction.findFirst({
where: { orderId: orderIdParam },
orderBy: { createdAt: 'desc' },
include: {
order: {
include: {
user: true,
orderItems: { include: { product: true } },
},
user: true,
},
});
}
user: true,
},
});
}
if (!transaction) {
throw new NotFoundException('تراکنش پرداخت در سیستم یافت نشد');
}
// If transaction is already verified, return successful details immediately
// --- IDEMPOTENCY CHECK ---
// If transaction is already marked as VERIFIED, return stored confirmation immediately
// without executing any duplicate side-effects (wallet increment, charity, status change, SMS).
if (transaction.status === 'VERIFIED') {
this.logger.log(
`Idempotency Guard: Transaction ${transaction.id} (trackId=${trackId}) is already VERIFIED. Skipping duplicate execution.`,
);
return {
success: true,
alreadyVerified: true,
@@ -257,6 +260,7 @@ export class PaymentService {
cardNumber: transaction.cardNumber,
amount: Number(transaction.amount),
orderId: transaction.orderId,
type: transaction.type,
message: 'تراکنش قبلاً با موفقیت تایید و پردازش شده است',
};
}
@@ -310,6 +314,39 @@ export class PaymentService {
};
}
// --- AMOUNT MATCH VERIFICATION ---
const expectedAmountRials = Number(
transaction.amountRials ||
Math.round(Number(transaction.amount) * 10),
);
if (
verifyRes.amount &&
Number(verifyRes.amount) > 0 &&
Number(verifyRes.amount) !== expectedAmountRials
) {
this.logger.error(
`Security Alert: Amount mismatch on trackId=${trackId}! Zibal reported ${verifyRes.amount} Rials, but expected ${expectedAmountRials} Rials in DB.`,
);
await this.prisma.paymentTransaction.update({
where: { id: transaction.id },
data: {
status: 'FAILED',
resultCode: verifyRes.result,
message: `مغایرت مالی: مبلغ تایید شده زیبال (${verifyRes.amount} ریال) با مبلغ سیستم (${expectedAmountRials} ریال) مطابقت ندارد.`,
},
});
return {
success: false,
status: 'FAILED',
trackId,
message: 'خطای امنیتی: مغایرت در مبلغ پرداخت شده با سفارش.',
orderId: transaction.orderId,
};
}
// SUCCESSFUL PAYMENT!
const refNumber = verifyRes.refNumber
? String(verifyRes.refNumber)
@@ -319,10 +356,11 @@ export class PaymentService {
? new Date(verifyRes.paidAt)
: new Date();
// Execute atomic status update with concurrency guard
await this.prisma.$transaction(async (tx) => {
// 1. Mark transaction as VERIFIED
await tx.paymentTransaction.update({
where: { id: transaction.id },
// Optimistic lock: only update if still PENDING (prevents race condition)
const updatedCount = await tx.paymentTransaction.updateMany({
where: { id: transaction.id, status: 'PENDING' },
data: {
status: 'VERIFIED',
resultCode: verifyRes.result,
@@ -333,6 +371,14 @@ export class PaymentService {
},
});
// If another concurrent thread verified it first, exit safely
if (updatedCount.count === 0) {
this.logger.warn(
`Concurrent execution detected for transaction ${transaction.id}. Handled safely.`,
);
return;
}
// 2. If it's an Order payment
if (transaction.type === 'ORDER' && transaction.orderId) {
await tx.order.update({
@@ -425,7 +471,77 @@ export class PaymentService {
}
/**
* 4. Get Payment Transaction Details
* 4. Auto-Reconciliation / Cron Job for Pending Transactions (استعلام تراکنش‌های بلاتکلیف)
*/
async reconcilePendingTransactions() {
this.logger.log('Starting pending transactions reconciliation job...');
// Find transactions that are PENDING and created between 5 minutes and 24 hours ago
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
const pendingTransactions = await this.prisma.paymentTransaction.findMany({
where: {
status: 'PENDING',
trackId: { not: null },
createdAt: {
gte: oneDayAgo,
lte: fiveMinutesAgo,
},
},
include: { order: true, user: true },
take: 50,
});
const results = {
total: pendingTransactions.length,
verified: 0,
failed: 0,
remainedPending: 0,
errors: 0,
};
for (const tx of pendingTransactions) {
if (!tx.trackId) continue;
try {
const inquiry = await this.zibalService.inquiryPayment(tx.trackId);
this.logger.log(
`Inquiry for trackId=${tx.trackId}: status=${inquiry.status}, result=${inquiry.result}`,
);
// Status 1 (paid & verified) or 2 (paid, unverified)
if (inquiry.status === 1 || inquiry.status === 2 || inquiry.result === 100) {
await this.verifyAndProcess(tx.trackId, '1', String(inquiry.status), tx.orderId || undefined);
results.verified++;
} else if (inquiry.status === 3 || inquiry.status === -2 || inquiry.result === 202) {
// Cancelled or failed
const msg = this.zibalService.getStatusMessage(inquiry.status || 3);
await this.prisma.paymentTransaction.update({
where: { id: tx.id },
data: {
status: 'FAILED',
resultCode: inquiry.result,
message: msg,
},
});
results.failed++;
} else {
results.remainedPending++;
}
} catch (err: unknown) {
results.errors++;
const msg = err instanceof Error ? err.message : String(err);
this.logger.warn(`Failed inquiry for trackId=${tx.trackId}: ${msg}`);
}
}
this.logger.log(`Reconciliation finished: ${JSON.stringify(results)}`);
return results;
}
/**
* 5. Get Payment Transaction Details by TrackID
*/
async getTransaction(trackId: string) {
const transaction = await this.prisma.paymentTransaction.findUnique({
@@ -438,6 +554,7 @@ export class PaymentService {
},
},
},
user: true,
},
});
@@ -458,6 +575,215 @@ export class PaymentService {
paidAt: transaction.paidAt,
createdAt: transaction.createdAt,
order: transaction.order,
user: transaction.user ? {
id: transaction.user.id,
firstName: transaction.user.firstName,
lastName: transaction.user.lastName,
mobile: transaction.user.mobile,
} : null,
};
}
/**
* 6. Admin: Get List of Transactions with Advanced Search & Filter
*/
async getAdminTransactions(filters: AdminTransactionFilterDto) {
const {
page = 1,
limit = 15,
search,
status,
gateway,
type,
startDate,
endDate,
minAmount,
maxAmount,
sortBy = 'createdAt',
sortOrder = 'desc',
} = filters;
const skip = (page - 1) * limit;
const where: Prisma.PaymentTransactionWhereInput = {};
if (status) {
where.status = status;
}
if (gateway) {
where.gateway = gateway;
}
if (type) {
where.type = type;
}
if (startDate || endDate) {
where.createdAt = {};
if (startDate) where.createdAt.gte = new Date(startDate);
if (endDate) where.createdAt.lte = new Date(endDate);
}
if (minAmount !== undefined || maxAmount !== undefined) {
where.amount = {};
if (minAmount !== undefined) where.amount.gte = new Prisma.Decimal(minAmount);
if (maxAmount !== undefined) where.amount.lte = new Prisma.Decimal(maxAmount);
}
if (search && search.trim() !== '') {
const s = search.trim();
where.OR = [
{ trackId: { contains: s, mode: 'insensitive' } },
{ refNumber: { contains: s, mode: 'insensitive' } },
{ cardNumber: { contains: s, mode: 'insensitive' } },
{ description: { contains: s, mode: 'insensitive' } },
{
user: {
OR: [
{ firstName: { contains: s, mode: 'insensitive' } },
{ lastName: { contains: s, mode: 'insensitive' } },
{ mobile: { contains: s, mode: 'insensitive' } },
],
},
},
{
order: {
trackingNumber: { contains: s, mode: 'insensitive' },
},
},
];
}
const [data, total] = await Promise.all([
this.prisma.paymentTransaction.findMany({
where,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
include: {
user: {
select: {
id: true,
firstName: true,
lastName: true,
mobile: true,
email: true,
},
},
order: {
select: {
id: true,
trackingNumber: true,
totalAmount: true,
status: true,
paymentMethod: true,
},
},
},
}),
this.prisma.paymentTransaction.count({ where }),
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
},
};
}
/**
* 7. Admin: Get Transaction Statistics
*/
async getAdminTransactionStats() {
const [
totalCount,
verifiedCount,
pendingCount,
failedCount,
verifiedSum,
todayVerified,
] = await Promise.all([
this.prisma.paymentTransaction.count(),
this.prisma.paymentTransaction.count({ where: { status: 'VERIFIED' } }),
this.prisma.paymentTransaction.count({ where: { status: 'PENDING' } }),
this.prisma.paymentTransaction.count({ where: { status: 'FAILED' } }),
this.prisma.paymentTransaction.aggregate({
_sum: { amount: true },
where: { status: 'VERIFIED' },
}),
this.prisma.paymentTransaction.aggregate({
_sum: { amount: true },
where: {
status: 'VERIFIED',
createdAt: {
gte: new Date(new Date().setHours(0, 0, 0, 0)),
},
},
}),
]);
const totalVolume = Number(verifiedSum._sum.amount || 0);
const todayVolume = Number(todayVerified._sum.amount || 0);
const successRate =
totalCount > 0 ? Math.round((verifiedCount / totalCount) * 100) : 0;
return {
totalCount,
verifiedCount,
pendingCount,
failedCount,
totalVolume,
todayVolume,
successRate,
};
}
/**
* 8. Admin: Perform Live Instant Inquiry on Zibal for a Transaction
*/
async adminLiveInquiry(transactionId: string) {
const transaction = await this.prisma.paymentTransaction.findUnique({
where: { id: transactionId },
include: { order: true, user: true },
});
if (!transaction) {
throw new NotFoundException('تراکنش یافت نشد');
}
if (!transaction.trackId) {
throw new BadRequestException('این تراکنش فاقد TrackId زیبال است');
}
const inquiryRes = await this.zibalService.inquiryPayment(transaction.trackId);
const statusMsg = this.zibalService.getStatusMessage(inquiryRes.status);
const resultMsg = this.zibalService.getResultMessage(inquiryRes.result);
// If transaction was PENDING and inquiry confirms payment, sync automatically
if (
transaction.status === 'PENDING' &&
(inquiryRes.status === 1 || inquiryRes.status === 2 || inquiryRes.result === 100)
) {
await this.verifyAndProcess(
transaction.trackId,
'1',
String(inquiryRes.status),
transaction.orderId || undefined,
);
}
return {
transactionId: transaction.id,
trackId: transaction.trackId,
currentDbStatus: transaction.status,
gatewayResponse: inquiryRes,
statusMessage: statusMsg,
resultMessage: resultMsg,
inquiredAt: new Date(),
};
}
}