test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -4,12 +4,12 @@ import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
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';
|
||||
} from "@nestjs/common";
|
||||
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";
|
||||
|
||||
export interface ClientMetadata {
|
||||
ipAddress?: string;
|
||||
@@ -41,11 +41,11 @@ export class PaymentService {
|
||||
});
|
||||
|
||||
if (!order) {
|
||||
throw new NotFoundException('سفارش مورد نظر یافت نشد');
|
||||
throw new NotFoundException("سفارش مورد نظر یافت نشد");
|
||||
}
|
||||
|
||||
if (['shipped', 'delivered'].includes(order.status)) {
|
||||
throw new BadRequestException('این سفارش قبلاً تکمیل و ارسال شده است');
|
||||
if (["shipped", "delivered"].includes(order.status)) {
|
||||
throw new BadRequestException("این سفارش قبلاً تکمیل و ارسال شده است");
|
||||
}
|
||||
|
||||
const amountTomans = Number(order.totalAmount);
|
||||
@@ -53,7 +53,7 @@ export class PaymentService {
|
||||
|
||||
if (amountRials < 1000) {
|
||||
throw new BadRequestException(
|
||||
'مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است',
|
||||
"مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ export class PaymentService {
|
||||
callbackUrl,
|
||||
orderId: order.id,
|
||||
mobile: order.user?.mobile || undefined,
|
||||
description: `پرداخت سفارش ${order.trackingNumber || ''} - پتشاپ کنینا`,
|
||||
description: `پرداخت سفارش ${order.trackingNumber || ""} - پتشاپ کنینا`,
|
||||
};
|
||||
|
||||
// Create a pending PaymentTransaction in database
|
||||
@@ -77,9 +77,9 @@ export class PaymentService {
|
||||
orderId: order.id,
|
||||
amount: new Prisma.Decimal(amountTomans),
|
||||
amountRials: BigInt(amountRials),
|
||||
gateway: 'zibal',
|
||||
status: 'PENDING',
|
||||
type: 'ORDER',
|
||||
gateway: "zibal",
|
||||
status: "PENDING",
|
||||
type: "ORDER",
|
||||
description: `پرداخت آنلاین سفارش ${order.trackingNumber || order.id}`,
|
||||
ipAddress: clientMeta?.ipAddress,
|
||||
userAgent: clientMeta?.userAgent,
|
||||
@@ -95,7 +95,7 @@ export class PaymentService {
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
resultCode: zibalRes.result,
|
||||
message: errorMsg,
|
||||
rawResponse: zibalRes as unknown as Prisma.InputJsonValue,
|
||||
@@ -130,7 +130,7 @@ export class PaymentService {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const stack = err instanceof Error ? err.stack : undefined;
|
||||
this.logger.error(`Error requesting payment from Zibal: ${msg}`, stack);
|
||||
throw new BadRequestException(msg || 'خطا در اتصال به درگاه پرداخت');
|
||||
throw new BadRequestException(msg || "خطا در اتصال به درگاه پرداخت");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,12 +144,12 @@ export class PaymentService {
|
||||
clientMeta?: ClientMetadata,
|
||||
) {
|
||||
if (amountTomans < 1000) {
|
||||
throw new BadRequestException('حداقل مبلغ افزایش موجودی ۱,۰۰۰ تومان است');
|
||||
throw new BadRequestException("حداقل مبلغ افزایش موجودی ۱,۰۰۰ تومان است");
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('کاربر یافت نشد');
|
||||
throw new NotFoundException("کاربر یافت نشد");
|
||||
}
|
||||
|
||||
const amountRials = Math.round(amountTomans * 10);
|
||||
@@ -170,9 +170,9 @@ export class PaymentService {
|
||||
userId,
|
||||
amount: new Prisma.Decimal(amountTomans),
|
||||
amountRials: BigInt(amountRials),
|
||||
gateway: 'zibal',
|
||||
status: 'PENDING',
|
||||
type: 'WALLET_TOPUP',
|
||||
gateway: "zibal",
|
||||
status: "PENDING",
|
||||
type: "WALLET_TOPUP",
|
||||
description: `افزایش موجودی کیف پول کاربر ${user.mobile}`,
|
||||
ipAddress: clientMeta?.ipAddress,
|
||||
userAgent: clientMeta?.userAgent,
|
||||
@@ -188,7 +188,7 @@ export class PaymentService {
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
resultCode: zibalRes.result,
|
||||
message: errorMsg,
|
||||
rawResponse: zibalRes as unknown as Prisma.InputJsonValue,
|
||||
@@ -218,7 +218,7 @@ export class PaymentService {
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
this.logger.error(`Error requesting wallet topup from Zibal: ${msg}`);
|
||||
throw new BadRequestException(msg || 'خطا در ارتباط با درگاه بانکی');
|
||||
throw new BadRequestException(msg || "خطا در ارتباط با درگاه بانکی");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@ export class PaymentService {
|
||||
if (!transaction && orderIdParam) {
|
||||
transaction = await this.prisma.paymentTransaction.findFirst({
|
||||
where: { orderId: orderIdParam },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
order: {
|
||||
include: {
|
||||
@@ -266,37 +266,37 @@ export class PaymentService {
|
||||
}
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش پرداخت در سیستم یافت نشد');
|
||||
throw new NotFoundException("تراکنش پرداخت در سیستم یافت نشد");
|
||||
}
|
||||
|
||||
// --- IDEMPOTENCY CHECK ---
|
||||
if (transaction.status === 'VERIFIED') {
|
||||
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,
|
||||
status: 'VERIFIED',
|
||||
status: "VERIFIED",
|
||||
trackId: transaction.trackId,
|
||||
refNumber: transaction.refNumber,
|
||||
cardNumber: transaction.cardNumber,
|
||||
amount: Number(transaction.amount),
|
||||
orderId: transaction.orderId,
|
||||
type: transaction.type,
|
||||
message: 'تراکنش قبلاً با موفقیت تایید و پردازش شده است',
|
||||
message: "تراکنش قبلاً با موفقیت تایید و پردازش شده است",
|
||||
};
|
||||
}
|
||||
|
||||
// If user cancelled or Zibal signaled failure at the gate
|
||||
if (successParam === '0' || statusParam === '3') {
|
||||
if (successParam === "0" || statusParam === "3") {
|
||||
const statusMessage = this.zibalService.getStatusMessage(
|
||||
statusParam || 3,
|
||||
);
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
message: statusMessage,
|
||||
ipAddress: clientMeta?.ipAddress || transaction.ipAddress,
|
||||
userAgent: clientMeta?.userAgent || transaction.userAgent,
|
||||
@@ -306,14 +306,14 @@ export class PaymentService {
|
||||
// Release any active inventory reservation for this order
|
||||
if (transaction.orderId) {
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { orderId: transaction.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'RELEASED' },
|
||||
where: { orderId: transaction.orderId, status: "ACTIVE" },
|
||||
data: { status: "RELEASED" },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
trackId,
|
||||
message: statusMessage,
|
||||
orderId: transaction.orderId,
|
||||
@@ -330,7 +330,7 @@ export class PaymentService {
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
resultCode: verifyRes.result,
|
||||
message: errorMsg,
|
||||
cardNumber: verifyRes.cardNumber,
|
||||
@@ -341,14 +341,14 @@ export class PaymentService {
|
||||
// Release inventory reservations on failure
|
||||
if (transaction.orderId) {
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { orderId: transaction.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'RELEASED' },
|
||||
where: { orderId: transaction.orderId, status: "ACTIVE" },
|
||||
data: { status: "RELEASED" },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
trackId,
|
||||
resultCode: verifyRes.result,
|
||||
message: errorMsg,
|
||||
@@ -373,7 +373,7 @@ export class PaymentService {
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transaction.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
resultCode: verifyRes.result,
|
||||
message: `مغایرت مالی: مبلغ تایید شده زیبال (${verifyRes.amount} ریال) با مبلغ سیستم (${expectedAmountRials} ریال) مطابقت ندارد.`,
|
||||
rawResponse: verifyRes as unknown as Prisma.InputJsonValue,
|
||||
@@ -382,9 +382,9 @@ export class PaymentService {
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
trackId,
|
||||
message: 'خطای امنیتی: مغایرت در مبلغ پرداخت شده با سفارش.',
|
||||
message: "خطای امنیتی: مغایرت در مبلغ پرداخت شده با سفارش.",
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
@@ -402,14 +402,14 @@ export class PaymentService {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
// Optimistic lock: only update if still PENDING
|
||||
const updatedCount = await tx.paymentTransaction.updateMany({
|
||||
where: { id: transaction.id, status: 'PENDING' },
|
||||
where: { id: transaction.id, status: "PENDING" },
|
||||
data: {
|
||||
status: 'VERIFIED',
|
||||
status: "VERIFIED",
|
||||
resultCode: verifyRes.result,
|
||||
refNumber,
|
||||
cardNumber,
|
||||
paidAt: paidDate,
|
||||
message: 'پرداخت با موفقیت انجام و تایید شد',
|
||||
message: "پرداخت با موفقیت انجام و تایید شد",
|
||||
rawResponse: verifyRes as unknown as Prisma.InputJsonValue,
|
||||
ipAddress: clientMeta?.ipAddress || transaction.ipAddress,
|
||||
userAgent: clientMeta?.userAgent || transaction.userAgent,
|
||||
@@ -424,19 +424,19 @@ export class PaymentService {
|
||||
}
|
||||
|
||||
// 2. If it's an Order payment -> Mark processing & Consume Inventory Reservation
|
||||
if (transaction.type === 'ORDER' && transaction.orderId) {
|
||||
if (transaction.type === "ORDER" && transaction.orderId) {
|
||||
await tx.order.update({
|
||||
where: { id: transaction.orderId },
|
||||
data: {
|
||||
status: 'processing',
|
||||
paymentMethod: 'online',
|
||||
status: "processing",
|
||||
paymentMethod: "online",
|
||||
},
|
||||
});
|
||||
|
||||
// Mark inventory reservations as CONSUMED and decrement product stock
|
||||
await tx.inventoryReservation.updateMany({
|
||||
where: { orderId: transaction.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'CONSUMED' },
|
||||
where: { orderId: transaction.orderId, status: "ACTIVE" },
|
||||
data: { status: "CONSUMED" },
|
||||
});
|
||||
|
||||
const orderWithItems = await tx.order.findUnique({
|
||||
@@ -456,7 +456,7 @@ export class PaymentService {
|
||||
if (updated.stock <= 0) {
|
||||
await tx.product.update({
|
||||
where: { id: item.productId },
|
||||
data: { stockStatus: 'OUT_OF_STOCK' },
|
||||
data: { stockStatus: "OUT_OF_STOCK" },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -490,7 +490,7 @@ export class PaymentService {
|
||||
}
|
||||
|
||||
// 3. If it's a Wallet Top-up
|
||||
if (transaction.type === 'WALLET_TOPUP') {
|
||||
if (transaction.type === "WALLET_TOPUP") {
|
||||
await tx.user.update({
|
||||
where: { id: transaction.userId },
|
||||
data: {
|
||||
@@ -504,8 +504,8 @@ export class PaymentService {
|
||||
data: {
|
||||
userId: transaction.userId,
|
||||
amount: transaction.amount,
|
||||
type: 'deposit',
|
||||
status: 'completed',
|
||||
type: "deposit",
|
||||
status: "completed",
|
||||
transactionReference: refNumber || `ZBL-${trackId}`,
|
||||
description: `افزایش اعتبار آنلاین از طریق درگاه زیبال (شناسه: ${trackId})`,
|
||||
},
|
||||
@@ -514,7 +514,7 @@ export class PaymentService {
|
||||
});
|
||||
|
||||
// Send SMS notification if order payment
|
||||
if (transaction.type === 'ORDER') {
|
||||
if (transaction.type === "ORDER") {
|
||||
const order = transaction.orderId
|
||||
? await this.prisma.order.findUnique({
|
||||
where: { id: transaction.orderId },
|
||||
@@ -533,11 +533,11 @@ export class PaymentService {
|
||||
const rawShipping = order?.shippingAddress;
|
||||
let shipping: Record<string, any> = {};
|
||||
|
||||
if (typeof rawShipping === 'object' && rawShipping !== null) {
|
||||
if (typeof rawShipping === "object" && rawShipping !== null) {
|
||||
shipping = rawShipping as Record<string, any>;
|
||||
} else if (typeof rawShipping === 'string') {
|
||||
} else if (typeof rawShipping === "string") {
|
||||
const trimmed = rawShipping.trim();
|
||||
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
|
||||
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
||||
try {
|
||||
shipping = JSON.parse(trimmed);
|
||||
} catch {
|
||||
@@ -554,13 +554,13 @@ export class PaymentService {
|
||||
shipping.fullName = recipientMatch[1]?.trim();
|
||||
if (!shipping.phone && recipientMatch[2])
|
||||
shipping.phone = recipientMatch[2]?.trim();
|
||||
text = text.replace(recipientMatch[0], '').trim();
|
||||
text = text.replace(recipientMatch[0], "").trim();
|
||||
}
|
||||
const postalMatch = text.match(/\(کد پستی:\s*([^)]+)\)/);
|
||||
if (postalMatch) {
|
||||
if (!shipping.postalCode)
|
||||
shipping.postalCode = postalMatch[1]?.trim();
|
||||
text = text.replace(postalMatch[0], '').trim();
|
||||
text = text.replace(postalMatch[0], "").trim();
|
||||
}
|
||||
const parts = text
|
||||
.split(/[،,]/)
|
||||
@@ -570,7 +570,7 @@ export class PaymentService {
|
||||
if (!shipping.province) shipping.province = parts[0];
|
||||
if (!shipping.city) shipping.city = parts[1];
|
||||
if (!shipping.address)
|
||||
shipping.address = parts.slice(2).join('، ');
|
||||
shipping.address = parts.slice(2).join("، ");
|
||||
} else if (parts.length === 2) {
|
||||
if (!shipping.province) shipping.province = parts[0];
|
||||
if (!shipping.address) shipping.address = parts[1];
|
||||
@@ -582,8 +582,8 @@ export class PaymentService {
|
||||
|
||||
const items = order?.orderItems || [];
|
||||
const itemsSummary = items
|
||||
.map((i: any) => `${i.product?.nameFa || 'محصول'} (${i.quantity})`)
|
||||
.join('، ');
|
||||
.map((i: any) => `${i.product?.nameFa || "محصول"} (${i.quantity})`)
|
||||
.join("، ");
|
||||
const itemCount = items.reduce(
|
||||
(sum: number, i: any) => sum + (i.quantity || 1),
|
||||
0,
|
||||
@@ -591,10 +591,10 @@ export class PaymentService {
|
||||
|
||||
const customerName = (
|
||||
transaction.user?.firstName
|
||||
? `${transaction.user.firstName} ${transaction.user.lastName || ''}`
|
||||
? `${transaction.user.firstName} ${transaction.user.lastName || ""}`
|
||||
: order?.user?.firstName
|
||||
? `${order.user.firstName} ${order.user.lastName || ''}`
|
||||
: shipping.fullName || 'مشتری'
|
||||
? `${order.user.firstName} ${order.user.lastName || ""}`
|
||||
: shipping.fullName || "مشتری"
|
||||
).trim();
|
||||
|
||||
const recipientFullName = (
|
||||
@@ -603,18 +603,18 @@ export class PaymentService {
|
||||
customerName
|
||||
).trim();
|
||||
|
||||
const recipientMobile = (shipping.phone || customerMobile || '').trim();
|
||||
const recipientMobile = (shipping.phone || customerMobile || "").trim();
|
||||
|
||||
const provinceCity = (
|
||||
shipping.province && shipping.city
|
||||
? `${shipping.province} - ${shipping.city}`
|
||||
: shipping.province || shipping.city || ''
|
||||
: shipping.province || shipping.city || ""
|
||||
).trim();
|
||||
|
||||
const addressDetail = (
|
||||
shipping.address ||
|
||||
shipping.detail ||
|
||||
(typeof rawShipping === 'string' ? rawShipping : '')
|
||||
(typeof rawShipping === "string" ? rawShipping : "")
|
||||
).trim();
|
||||
|
||||
const orderData = {
|
||||
@@ -623,28 +623,28 @@ export class PaymentService {
|
||||
transaction.order?.trackingNumber ||
|
||||
transaction.orderId ||
|
||||
transaction.id,
|
||||
amount: Number(transaction.amount).toLocaleString('fa-IR'),
|
||||
amount: Number(transaction.amount).toLocaleString("fa-IR"),
|
||||
customerName,
|
||||
customerPhone: customerMobile || '',
|
||||
customerPhone: customerMobile || "",
|
||||
recipientName: recipientFullName,
|
||||
recipientPhone: recipientMobile,
|
||||
provinceCity: provinceCity || 'ثبت نشده',
|
||||
postalCode: shipping.postalCode || shipping.zipCode || '',
|
||||
address: addressDetail || '',
|
||||
provinceCity: provinceCity || "ثبت نشده",
|
||||
postalCode: shipping.postalCode || shipping.zipCode || "",
|
||||
address: addressDetail || "",
|
||||
itemsSummary,
|
||||
itemCount: String(itemCount),
|
||||
paymentMethod: 'آنلاین',
|
||||
refNumber: refNumber || '',
|
||||
orderDate: new Date().toLocaleDateString('fa-IR'),
|
||||
paymentMethod: "آنلاین",
|
||||
refNumber: refNumber || "",
|
||||
orderDate: new Date().toLocaleDateString("fa-IR"),
|
||||
};
|
||||
|
||||
this.smsService.triggerEvent('ORDER_PAID', orderData).catch((err) => {
|
||||
this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => {
|
||||
this.logger.warn(`Could not trigger SMS event ORDER_PAID: ${err}`);
|
||||
});
|
||||
}
|
||||
|
||||
// Send SMS notification if wallet top-up
|
||||
if (transaction.type === 'WALLET_TOPUP' && transaction.userId) {
|
||||
if (transaction.type === "WALLET_TOPUP" && transaction.userId) {
|
||||
try {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: transaction.userId },
|
||||
@@ -652,20 +652,20 @@ export class PaymentService {
|
||||
if (user?.mobile) {
|
||||
const customerFullName = (
|
||||
user.firstName
|
||||
? `${user.firstName} ${user.lastName || ''}`
|
||||
: 'کاربر گرامی'
|
||||
? `${user.firstName} ${user.lastName || ""}`
|
||||
: "کاربر گرامی"
|
||||
).trim();
|
||||
const topupData = {
|
||||
customerName: customerFullName,
|
||||
customerPhone: user.mobile,
|
||||
amount: Number(transaction.amount || 0).toLocaleString('fa-IR'),
|
||||
balance: Number(user.walletBalance || 0).toLocaleString('fa-IR'),
|
||||
reason: 'شارژ آنلاین از طریق درگاه بانکی',
|
||||
date: new Date().toLocaleDateString('fa-IR'),
|
||||
amount: Number(transaction.amount || 0).toLocaleString("fa-IR"),
|
||||
balance: Number(user.walletBalance || 0).toLocaleString("fa-IR"),
|
||||
reason: "شارژ آنلاین از طریق درگاه بانکی",
|
||||
date: new Date().toLocaleDateString("fa-IR"),
|
||||
};
|
||||
|
||||
this.smsService
|
||||
.triggerEvent('WALLET_CHARGED', topupData)
|
||||
.triggerEvent("WALLET_CHARGED", topupData)
|
||||
.catch((err) => {
|
||||
this.logger.warn(
|
||||
`Could not trigger SMS event WALLET_CHARGED: ${err}`,
|
||||
@@ -679,14 +679,14 @@ export class PaymentService {
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: 'VERIFIED',
|
||||
status: "VERIFIED",
|
||||
trackId,
|
||||
refNumber,
|
||||
cardNumber,
|
||||
amount: Number(transaction.amount),
|
||||
orderId: transaction.orderId,
|
||||
type: transaction.type,
|
||||
message: 'پرداخت با موفقیت انجام شد',
|
||||
message: "پرداخت با موفقیت انجام شد",
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
@@ -694,9 +694,9 @@ export class PaymentService {
|
||||
this.logger.error(`Error during verify: ${msg}`, stack);
|
||||
return {
|
||||
success: false,
|
||||
status: 'ERROR',
|
||||
status: "ERROR",
|
||||
trackId,
|
||||
message: msg || 'خطا در فرایند تایید تراکنش',
|
||||
message: msg || "خطا در فرایند تایید تراکنش",
|
||||
orderId: transaction.orderId,
|
||||
};
|
||||
}
|
||||
@@ -706,14 +706,14 @@ export class PaymentService {
|
||||
* 4. Auto-Reconciliation / Cron Job for Pending Transactions
|
||||
*/
|
||||
async reconcilePendingTransactions() {
|
||||
this.logger.log('Starting pending transactions reconciliation job...');
|
||||
this.logger.log("Starting pending transactions reconciliation job...");
|
||||
|
||||
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',
|
||||
status: "PENDING",
|
||||
trackId: { not: null },
|
||||
createdAt: {
|
||||
gte: oneDayAgo,
|
||||
@@ -748,7 +748,7 @@ export class PaymentService {
|
||||
) {
|
||||
await this.verifyAndProcess(
|
||||
tx.trackId,
|
||||
'1',
|
||||
"1",
|
||||
String(inquiry.status),
|
||||
tx.orderId || undefined,
|
||||
);
|
||||
@@ -762,7 +762,7 @@ export class PaymentService {
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: tx.id },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
resultCode: inquiry.result,
|
||||
message: msg,
|
||||
rawResponse: inquiry as unknown as Prisma.InputJsonValue,
|
||||
@@ -771,8 +771,8 @@ export class PaymentService {
|
||||
|
||||
if (tx.orderId) {
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { orderId: tx.orderId, status: 'ACTIVE' },
|
||||
data: { status: 'RELEASED' },
|
||||
where: { orderId: tx.orderId, status: "ACTIVE" },
|
||||
data: { status: "RELEASED" },
|
||||
});
|
||||
}
|
||||
results.failed++;
|
||||
@@ -789,8 +789,8 @@ export class PaymentService {
|
||||
// Also release all expired reservations
|
||||
const now = new Date();
|
||||
await this.prisma.inventoryReservation.updateMany({
|
||||
where: { status: 'ACTIVE', expiresAt: { lte: now } },
|
||||
data: { status: 'RELEASED' },
|
||||
where: { status: "ACTIVE", expiresAt: { lte: now } },
|
||||
data: { status: "RELEASED" },
|
||||
});
|
||||
|
||||
this.logger.log(`Reconciliation finished: ${JSON.stringify(results)}`);
|
||||
@@ -820,7 +820,7 @@ export class PaymentService {
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
throw new NotFoundException("تراکنش یافت نشد");
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -830,12 +830,12 @@ export class PaymentService {
|
||||
transaction.userId !== requestingUserId
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'شما دسترسی به اطلاعات این تراکنش را ندارید',
|
||||
"شما دسترسی به اطلاعات این تراکنش را ندارید",
|
||||
);
|
||||
}
|
||||
|
||||
const maskedCard = transaction.cardNumber
|
||||
? transaction.cardNumber.replace(/(\d{6})\d{6}(\d{4})/, '$1******$2')
|
||||
? transaction.cardNumber.replace(/(\d{6})\d{6}(\d{4})/, "$1******$2")
|
||||
: null;
|
||||
|
||||
return {
|
||||
@@ -885,8 +885,8 @@ export class PaymentService {
|
||||
endDate,
|
||||
minAmount,
|
||||
maxAmount,
|
||||
sortBy = 'createdAt',
|
||||
sortOrder = 'desc',
|
||||
sortBy = "createdAt",
|
||||
sortOrder = "desc",
|
||||
} = filters;
|
||||
|
||||
const skip = (page - 1) * limit;
|
||||
@@ -918,25 +918,25 @@ export class PaymentService {
|
||||
where.amount.lte = new Prisma.Decimal(maxAmount);
|
||||
}
|
||||
|
||||
if (search && search.trim() !== '') {
|
||||
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' } },
|
||||
{ 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' } },
|
||||
{ firstName: { contains: s, mode: "insensitive" } },
|
||||
{ lastName: { contains: s, mode: "insensitive" } },
|
||||
{ mobile: { contains: s, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
order: {
|
||||
trackingNumber: { contains: s, mode: 'insensitive' },
|
||||
trackingNumber: { contains: s, mode: "insensitive" },
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -996,17 +996,17 @@ export class PaymentService {
|
||||
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.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' },
|
||||
where: { status: "VERIFIED" },
|
||||
}),
|
||||
this.prisma.paymentTransaction.aggregate({
|
||||
_sum: { amount: true },
|
||||
where: {
|
||||
status: 'VERIFIED',
|
||||
status: "VERIFIED",
|
||||
createdAt: {
|
||||
gte: new Date(new Date().setHours(0, 0, 0, 0)),
|
||||
},
|
||||
@@ -1040,11 +1040,11 @@ export class PaymentService {
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
throw new NotFoundException("تراکنش یافت نشد");
|
||||
}
|
||||
|
||||
if (!transaction.trackId) {
|
||||
throw new BadRequestException('این تراکنش فاقد TrackId زیبال است');
|
||||
throw new BadRequestException("این تراکنش فاقد TrackId زیبال است");
|
||||
}
|
||||
|
||||
const inquiryRes = await this.zibalService.inquiryPayment(
|
||||
@@ -1056,14 +1056,14 @@ export class PaymentService {
|
||||
const resultMsg = this.zibalService.getResultMessage(inquiryRes.result);
|
||||
|
||||
if (
|
||||
transaction.status === 'PENDING' &&
|
||||
transaction.status === "PENDING" &&
|
||||
(inquiryRes.status === 1 ||
|
||||
inquiryRes.status === 2 ||
|
||||
inquiryRes.result === 100)
|
||||
) {
|
||||
await this.verifyAndProcess(
|
||||
transaction.trackId,
|
||||
'1',
|
||||
"1",
|
||||
String(inquiryRes.status),
|
||||
transaction.orderId || undefined,
|
||||
);
|
||||
@@ -1120,26 +1120,26 @@ export class PaymentService {
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
throw new NotFoundException("تراکنش یافت نشد");
|
||||
}
|
||||
|
||||
if (transaction.status === 'VERIFIED') {
|
||||
throw new BadRequestException('این تراکنش قبلاً تایید شده است');
|
||||
if (transaction.status === "VERIFIED") {
|
||||
throw new BadRequestException("این تراکنش قبلاً تایید شده است");
|
||||
}
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.paymentTransaction.update({
|
||||
where: { id: transactionId },
|
||||
data: {
|
||||
status: 'VERIFIED',
|
||||
status: "VERIFIED",
|
||||
message:
|
||||
adminNote ||
|
||||
'تایید دستی توسط مدیر سیستم (کارت به کارت / فیش بانکی)',
|
||||
"تایید دستی توسط مدیر سیستم (کارت به کارت / فیش بانکی)",
|
||||
paidAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
if (transaction.type === 'WALLET_TOPUP') {
|
||||
if (transaction.type === "WALLET_TOPUP") {
|
||||
await tx.user.update({
|
||||
where: { id: transaction.userId },
|
||||
data: {
|
||||
@@ -1151,23 +1151,23 @@ export class PaymentService {
|
||||
data: {
|
||||
userId: transaction.userId,
|
||||
amount: transaction.amount,
|
||||
type: 'deposit',
|
||||
status: 'completed',
|
||||
description: `افزایش موجودی دستی تایید شده توسط ادمین (${adminNote || 'کارت به کارت'})`,
|
||||
type: "deposit",
|
||||
status: "completed",
|
||||
description: `افزایش موجودی دستی تایید شده توسط ادمین (${adminNote || "کارت به کارت"})`,
|
||||
},
|
||||
});
|
||||
} else if (transaction.type === 'ORDER' && transaction.orderId) {
|
||||
} else if (transaction.type === "ORDER" && transaction.orderId) {
|
||||
await tx.order.update({
|
||||
where: { id: transaction.orderId },
|
||||
data: {
|
||||
status: 'processing',
|
||||
paymentMethod: 'card_to_card',
|
||||
status: "processing",
|
||||
paymentMethod: "card_to_card",
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (transaction.type === 'WALLET_TOPUP' && transaction.userId) {
|
||||
if (transaction.type === "WALLET_TOPUP" && transaction.userId) {
|
||||
try {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: transaction.userId },
|
||||
@@ -1175,20 +1175,20 @@ export class PaymentService {
|
||||
if (user?.mobile) {
|
||||
const customerFullName = (
|
||||
user.firstName
|
||||
? `${user.firstName} ${user.lastName || ''}`
|
||||
: 'کاربر گرامی'
|
||||
? `${user.firstName} ${user.lastName || ""}`
|
||||
: "کاربر گرامی"
|
||||
).trim();
|
||||
const topupData = {
|
||||
customerName: customerFullName,
|
||||
customerPhone: user.mobile,
|
||||
amount: Number(transaction.amount || 0).toLocaleString('fa-IR'),
|
||||
balance: Number(user.walletBalance || 0).toLocaleString('fa-IR'),
|
||||
reason: adminNote || 'افزایش موجودی (کارت به کارت / فیش بانکی)',
|
||||
date: new Date().toLocaleDateString('fa-IR'),
|
||||
amount: Number(transaction.amount || 0).toLocaleString("fa-IR"),
|
||||
balance: Number(user.walletBalance || 0).toLocaleString("fa-IR"),
|
||||
reason: adminNote || "افزایش موجودی (کارت به کارت / فیش بانکی)",
|
||||
date: new Date().toLocaleDateString("fa-IR"),
|
||||
};
|
||||
|
||||
this.smsService
|
||||
.triggerEvent('WALLET_CHARGED', topupData)
|
||||
.triggerEvent("WALLET_CHARGED", topupData)
|
||||
.catch((err) => {
|
||||
this.logger.warn(
|
||||
`Could not trigger SMS event WALLET_CHARGED: ${err}`,
|
||||
@@ -1202,7 +1202,7 @@ export class PaymentService {
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'تراکنش با موفقیت به صورت دستی تایید و اعمال شد',
|
||||
message: "تراکنش با موفقیت به صورت دستی تایید و اعمال شد",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1215,20 +1215,20 @@ export class PaymentService {
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
throw new NotFoundException("تراکنش یافت نشد");
|
||||
}
|
||||
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transactionId },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
message: reason || 'رد شده توسط ادمین سیستم',
|
||||
status: "FAILED",
|
||||
message: reason || "رد شده توسط ادمین سیستم",
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'تراکنش به عنوان ناموفق/رد شده علامتگذاری شد',
|
||||
message: "تراکنش به عنوان ناموفق/رد شده علامتگذاری شد",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1268,9 +1268,9 @@ export class PaymentService {
|
||||
}
|
||||
}
|
||||
|
||||
if (order && order.refundStatus === 'gateway') {
|
||||
if (order && order.refundStatus === "gateway") {
|
||||
throw new BadRequestException(
|
||||
'برای این سفارش قبلاً استرداد درگاه بانکی انجام شده است',
|
||||
"برای این سفارش قبلاً استرداد درگاه بانکی انجام شده است",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1296,7 +1296,7 @@ export class PaymentService {
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
// If order was previously refunded to wallet, deduct that amount from user's wallet!
|
||||
if (order.refundStatus === 'wallet' && order.userId) {
|
||||
if (order.refundStatus === "wallet" && order.userId) {
|
||||
const deductionAmount = Number(
|
||||
order.refundedAmount || refundAmountTomans,
|
||||
);
|
||||
@@ -1311,8 +1311,8 @@ export class PaymentService {
|
||||
data: {
|
||||
userId: order.userId,
|
||||
amount: deductionAmount,
|
||||
type: 'withdraw',
|
||||
status: 'completed',
|
||||
type: "withdraw",
|
||||
status: "completed",
|
||||
description: `کسر موجودی کیف پول به علت استرداد بانکی سفارش #${order.trackingNumber || order.id.slice(0, 8)} از طریق زیبال`,
|
||||
},
|
||||
});
|
||||
@@ -1322,10 +1322,10 @@ export class PaymentService {
|
||||
await tx.order.update({
|
||||
where: { id: order.id },
|
||||
data: {
|
||||
status: 'cancelled',
|
||||
refundStatus: 'gateway',
|
||||
status: "cancelled",
|
||||
refundStatus: "gateway",
|
||||
refundedAmount: refundAmountTomans,
|
||||
refundMethod: 'zibal',
|
||||
refundMethod: "zibal",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user