import { Injectable, NotFoundException, 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"; export interface ClientMetadata { ipAddress?: string; userAgent?: string; } @Injectable() export class PaymentService { private readonly logger = new Logger(PaymentService.name); constructor( private readonly prisma: PrismaService, private readonly zibalService: ZibalService, private readonly smsService: SmsService, ) {} /** * 1. Initiate Online Payment for an Order via Zibal */ async initiateOrderPayment( userId: string, orderId: string, customCallbackUrl?: string, clientMeta?: ClientMetadata, ) { const order = await this.prisma.order.findFirst({ where: { id: orderId, userId }, include: { user: true }, }); if (!order) { throw new NotFoundException("سفارش مورد نظر یافت نشد"); } if (["shipped", "delivered"].includes(order.status)) { throw new BadRequestException("این سفارش قبلاً تکمیل و ارسال شده است"); } const amountTomans = Number(order.totalAmount); const amountRials = Math.round(amountTomans * 10); if (amountRials < 1000) { throw new BadRequestException( "مبلغ سفارش کمتر از حداقل مجاز درگاه بانکی (۱,۰۰۰ ریال) است", ); } const backendUrl = await this.zibalService.getBackendUrl(); const callbackUrl = customCallbackUrl || `${backendUrl}/payment/zibal/callback?orderId=${order.id}`; const requestPayload = { amountRials, callbackUrl, orderId: order.id, mobile: order.user?.mobile || undefined, description: `پرداخت سفارش ${order.trackingNumber || ""} - پت‌شاپ کنینا`, }; // Create a pending PaymentTransaction in database const transaction = await this.prisma.paymentTransaction.create({ data: { userId, orderId: order.id, amount: new Prisma.Decimal(amountTomans), amountRials: BigInt(amountRials), gateway: "zibal", status: "PENDING", type: "ORDER", description: `پرداخت آنلاین سفارش ${order.trackingNumber || order.id}`, ipAddress: clientMeta?.ipAddress, userAgent: clientMeta?.userAgent, rawRequest: requestPayload, }, }); try { const zibalRes = await this.zibalService.requestPayment(requestPayload); if (zibalRes.result !== 100) { const errorMsg = this.zibalService.getResultMessage(zibalRes.result); await this.prisma.paymentTransaction.update({ where: { id: transaction.id }, data: { status: "FAILED", resultCode: zibalRes.result, message: errorMsg, rawResponse: zibalRes as unknown as Prisma.InputJsonValue, }, }); throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`); } const trackId = String(zibalRes.trackId); // Update transaction with trackId await this.prisma.paymentTransaction.update({ where: { id: transaction.id }, data: { trackId, resultCode: zibalRes.result, message: zibalRes.message, rawResponse: zibalRes as unknown as Prisma.InputJsonValue, }, }); const paymentUrl = this.zibalService.getStartUrl(trackId); return { success: true, trackId, paymentUrl, orderId: order.id, amount: amountTomans, }; } catch (err: unknown) { 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 || "خطا در اتصال به درگاه پرداخت"); } } /** * 2. Initiate Online Wallet Top-Up via Zibal */ async initiateWalletTopup( userId: string, amountTomans: number, customCallbackUrl?: string, clientMeta?: ClientMetadata, ) { if (amountTomans < 1000) { throw new BadRequestException("حداقل مبلغ افزایش موجودی ۱,۰۰۰ تومان است"); } const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (!user) { throw new NotFoundException("کاربر یافت نشد"); } const amountRials = Math.round(amountTomans * 10); const backendUrl = await this.zibalService.getBackendUrl(); const callbackUrl = customCallbackUrl || `${backendUrl}/payment/zibal/callback?type=WALLET_TOPUP`; const requestPayload = { amountRials, callbackUrl, mobile: user.mobile || undefined, description: `شارژ کیف پول - پت شاپ کنینا`, }; const transaction = await this.prisma.paymentTransaction.create({ data: { userId, amount: new Prisma.Decimal(amountTomans), amountRials: BigInt(amountRials), gateway: "zibal", status: "PENDING", type: "WALLET_TOPUP", description: `افزایش موجودی کیف پول کاربر ${user.mobile}`, ipAddress: clientMeta?.ipAddress, userAgent: clientMeta?.userAgent, rawRequest: requestPayload, }, }); try { const zibalRes = await this.zibalService.requestPayment(requestPayload); if (zibalRes.result !== 100) { const errorMsg = this.zibalService.getResultMessage(zibalRes.result); await this.prisma.paymentTransaction.update({ where: { id: transaction.id }, data: { status: "FAILED", resultCode: zibalRes.result, message: errorMsg, rawResponse: zibalRes as unknown as Prisma.InputJsonValue, }, }); throw new BadRequestException(`خطا در ایجاد تراکنش زیبال: ${errorMsg}`); } const trackId = String(zibalRes.trackId); await this.prisma.paymentTransaction.update({ where: { id: transaction.id }, data: { trackId, resultCode: zibalRes.result, message: zibalRes.message, rawResponse: zibalRes as unknown as Prisma.InputJsonValue, }, }); return { success: true, trackId, paymentUrl: this.zibalService.getStartUrl(trackId), amount: amountTomans, }; } 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 || "خطا در ارتباط با درگاه بانکی"); } } /** * 3. Verify & Process Callback from Zibal (With Idempotency, Amount Match & Inventory Hold Release/Consume) */ async verifyAndProcess( trackId: string, successParam?: string, statusParam?: string, orderIdParam?: string, clientMeta?: ClientMetadata, ) { this.logger.log( `Processing callback for trackId=${trackId}, success=${successParam}, status=${statusParam}, orderId=${orderIdParam}`, ); let transaction = await this.prisma.paymentTransaction.findUnique({ where: { trackId }, include: { order: { include: { user: true, orderItems: { include: { product: true } }, }, }, user: 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, }, }); } if (!transaction) { throw new NotFoundException("تراکنش پرداخت در سیستم یافت نشد"); } // --- IDEMPOTENCY CHECK --- 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", trackId: transaction.trackId, refNumber: transaction.refNumber, cardNumber: transaction.cardNumber, amount: Number(transaction.amount), orderId: transaction.orderId, type: transaction.type, message: "تراکنش قبلاً با موفقیت تایید و پردازش شده است", }; } // If user cancelled or Zibal signaled failure at the gate if (successParam === "0" || statusParam === "3") { const statusMessage = this.zibalService.getStatusMessage( statusParam || 3, ); await this.prisma.paymentTransaction.update({ where: { id: transaction.id }, data: { status: "FAILED", message: statusMessage, ipAddress: clientMeta?.ipAddress || transaction.ipAddress, userAgent: clientMeta?.userAgent || transaction.userAgent, }, }); // 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" }, }); } return { success: false, status: "FAILED", trackId, message: statusMessage, orderId: transaction.orderId, }; } // Call Zibal verify endpoint try { const verifyRes = await this.zibalService.verifyPayment(trackId); const isSuccess = verifyRes.result === 100 || verifyRes.result === 201; if (!isSuccess) { const errorMsg = this.zibalService.getResultMessage(verifyRes.result); await this.prisma.paymentTransaction.update({ where: { id: transaction.id }, data: { status: "FAILED", resultCode: verifyRes.result, message: errorMsg, cardNumber: verifyRes.cardNumber, rawResponse: verifyRes as unknown as Prisma.InputJsonValue, }, }); // Release inventory reservations on failure if (transaction.orderId) { await this.prisma.inventoryReservation.updateMany({ where: { orderId: transaction.orderId, status: "ACTIVE" }, data: { status: "RELEASED" }, }); } return { success: false, status: "FAILED", trackId, resultCode: verifyRes.result, message: errorMsg, orderId: transaction.orderId, }; } // --- 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} ریال) مطابقت ندارد.`, rawResponse: verifyRes as unknown as Prisma.InputJsonValue, }, }); return { success: false, status: "FAILED", trackId, message: "خطای امنیتی: مغایرت در مبلغ پرداخت شده با سفارش.", orderId: transaction.orderId, }; } // SUCCESSFUL PAYMENT! const refNumber = verifyRes.refNumber ? String(verifyRes.refNumber) : undefined; const cardNumber = verifyRes.cardNumber || undefined; const paidDate = verifyRes.paidAt ? new Date(verifyRes.paidAt) : new Date(); // Execute atomic status update with concurrency guard 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" }, data: { status: "VERIFIED", resultCode: verifyRes.result, refNumber, cardNumber, paidAt: paidDate, message: "پرداخت با موفقیت انجام و تایید شد", rawResponse: verifyRes as unknown as Prisma.InputJsonValue, ipAddress: clientMeta?.ipAddress || transaction.ipAddress, userAgent: clientMeta?.userAgent || transaction.userAgent, }, }); if (updatedCount.count === 0) { this.logger.warn( `Concurrent execution detected for transaction ${transaction.id}. Handled safely.`, ); return; } // 2. If it's an Order payment -> Mark processing & Consume Inventory Reservation if (transaction.type === "ORDER" && transaction.orderId) { await tx.order.update({ where: { id: transaction.orderId }, data: { 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" }, }); const orderWithItems = await tx.order.findUnique({ where: { id: transaction.orderId }, include: { orderItems: true }, }); if (orderWithItems?.orderItems) { for (const item of orderWithItems.orderItems) { if (item.productId) { // BE-05: Atomic decrement with inventory constraint guard let updateCount = 1; if (typeof (tx as any).$executeRaw === 'function') { updateCount = await tx.$executeRaw` UPDATE products SET stock = stock - ${item.quantity}, stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity} `; } else { const updated = await tx.product.update({ where: { id: item.productId }, data: { stock: { decrement: item.quantity } }, }); if (updated.stock <= 0) { await tx.product.update({ where: { id: item.productId }, data: { stockStatus: "OUT_OF_STOCK" }, }); } } if (updateCount === 0) { this.logger.error( `[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.` ); } } } } // If charity donation was made, update user's total charity if ( transaction.order && Number(transaction.order.charityDonation) > 0 ) { await tx.user.update({ where: { id: transaction.userId }, data: { charityDonationTotal: { increment: Number(transaction.order.charityDonation), }, }, }); } // Increment coupon usedCount if coupon was applied if (transaction.order && transaction.order.couponId) { await tx.coupon .update({ where: { id: transaction.order.couponId }, data: { usedCount: { increment: 1 } }, }) .catch(() => {}); } } // 3. If it's a Wallet Top-up if (transaction.type === "WALLET_TOPUP") { await tx.user.update({ where: { id: transaction.userId }, data: { walletBalance: { increment: Number(transaction.amount), }, }, }); await tx.walletTransaction.create({ data: { userId: transaction.userId, amount: transaction.amount, type: "deposit", status: "completed", transactionReference: refNumber || `ZBL-${trackId}`, description: `افزایش اعتبار آنلاین از طریق درگاه زیبال (شناسه: ${trackId})`, }, }); } }); // Send SMS notification if order payment if (transaction.type === "ORDER") { const order = transaction.orderId ? await this.prisma.order.findUnique({ where: { id: transaction.orderId }, include: { user: true, orderItems: { include: { product: true } }, }, }) : transaction.order; const customerMobile = order?.user?.mobile || transaction.user?.mobile || (transaction.rawRequest as { mobile?: string })?.mobile; const rawShipping = order?.shippingAddress; let shipping: Record = {}; if (typeof rawShipping === "object" && rawShipping !== null) { shipping = rawShipping as Record; } else if (typeof rawShipping === "string") { const trimmed = rawShipping.trim(); if (trimmed.startsWith("{") && trimmed.endsWith("}")) { try { shipping = JSON.parse(trimmed); } catch { shipping = {}; } } if (!shipping.province || !shipping.address) { let text = trimmed; const recipientMatch = text.match( /\(گیرنده:\s*([^-)]+)(?:-\s*([^)]+))?\)/, ); if (recipientMatch) { if (!shipping.fullName) shipping.fullName = recipientMatch[1]?.trim(); if (!shipping.phone && recipientMatch[2]) shipping.phone = recipientMatch[2]?.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(); } const parts = text .split(/[،,]/) .map((p) => p.trim()) .filter(Boolean); if (parts.length >= 3) { if (!shipping.province) shipping.province = parts[0]; if (!shipping.city) shipping.city = parts[1]; if (!shipping.address) 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]; } else if (parts.length === 1 && !shipping.address) { shipping.address = parts[0]; } } } const items = order?.orderItems || []; const itemsSummary = items .map((i: any) => `${i.product?.nameFa || "محصول"} (${i.quantity})`) .join("، "); const itemCount = items.reduce( (sum: number, i: any) => sum + (i.quantity || 1), 0, ); const customerName = ( transaction.user?.firstName ? `${transaction.user.firstName} ${transaction.user.lastName || ""}` : order?.user?.firstName ? `${order.user.firstName} ${order.user.lastName || ""}` : shipping.fullName || "مشتری" ).trim(); const recipientFullName = ( shipping.fullName || shipping.receptorName || customerName ).trim(); const recipientMobile = (shipping.phone || customerMobile || "").trim(); const provinceCity = ( shipping.province && shipping.city ? `${shipping.province} - ${shipping.city}` : shipping.province || shipping.city || "" ).trim(); const addressDetail = ( shipping.address || shipping.detail || (typeof rawShipping === "string" ? rawShipping : "") ).trim(); const orderData = { orderNumber: order?.trackingNumber || transaction.order?.trackingNumber || transaction.orderId || transaction.id, amount: Number(transaction.amount).toLocaleString("fa-IR"), customerName, customerPhone: customerMobile || "", recipientName: recipientFullName, recipientPhone: recipientMobile, provinceCity: provinceCity || "ثبت نشده", postalCode: shipping.postalCode || shipping.zipCode || "", address: addressDetail || "", itemsSummary, itemCount: String(itemCount), paymentMethod: "آنلاین", refNumber: refNumber || "", orderDate: new Date().toLocaleDateString("fa-IR"), }; 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) { try { const user = await this.prisma.user.findUnique({ where: { id: transaction.userId }, }); if (user?.mobile) { const customerFullName = ( user.firstName ? `${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"), }; this.smsService .triggerEvent("WALLET_CHARGED", topupData) .catch((err) => { this.logger.warn( `Could not trigger SMS event WALLET_CHARGED: ${err}`, ); }); } } catch (err) { this.logger.warn(`Error dispatching WALLET_CHARGED SMS: ${err}`); } } return { success: true, status: "VERIFIED", trackId, refNumber, cardNumber, amount: Number(transaction.amount), orderId: transaction.orderId, type: transaction.type, message: "پرداخت با موفقیت انجام شد", }; } catch (err: unknown) { const msg = err instanceof Error ? err.message : String(err); const stack = err instanceof Error ? err.stack : undefined; this.logger.error(`Error during verify: ${msg}`, stack); return { success: false, status: "ERROR", trackId, message: msg || "خطا در فرایند تایید تراکنش", orderId: transaction.orderId, }; } } /** * 4. Auto-Reconciliation / Cron Job for Pending Transactions */ async reconcilePendingTransactions() { 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", 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}`, ); 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 ) { 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, rawResponse: inquiry as unknown as Prisma.InputJsonValue, }, }); if (tx.orderId) { await this.prisma.inventoryReservation.updateMany({ where: { orderId: tx.orderId, status: "ACTIVE" }, data: { status: "RELEASED" }, }); } 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}`); } } // Also release all expired reservations const now = new Date(); await this.prisma.inventoryReservation.updateMany({ where: { status: "ACTIVE", expiresAt: { lte: now } }, data: { status: "RELEASED" }, }); this.logger.log(`Reconciliation finished: ${JSON.stringify(results)}`); return results; } /** * 5. Get Payment Transaction Details by TrackID */ async getTransaction( trackId: string, requestingUserId?: string, isAdmin = false, ) { const transaction = await this.prisma.paymentTransaction.findUnique({ where: { trackId }, include: { order: { include: { orderItems: { include: { product: true }, }, }, }, user: true, }, }); if (!transaction) { throw new NotFoundException("تراکنش یافت نشد"); } if ( !isAdmin && requestingUserId && transaction.userId && transaction.userId !== requestingUserId ) { throw new ForbiddenException( "شما دسترسی به اطلاعات این تراکنش را ندارید", ); } const maskedCard = transaction.cardNumber ? transaction.cardNumber.replace(/(\d{6})\d{6}(\d{4})/, "$1******$2") : null; return { id: transaction.id, trackId: transaction.trackId, refNumber: transaction.refNumber, amount: Number(transaction.amount), status: transaction.status, message: transaction.message, gateway: transaction.gateway, type: transaction.type, cardNumber: isAdmin ? transaction.cardNumber : maskedCard, 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: isAdmin ? transaction.user.mobile : undefined, } : null, ...(isAdmin ? { ipAddress: transaction.ipAddress, userAgent: transaction.userAgent, rawRequest: transaction.rawRequest, rawResponse: transaction.rawResponse, } : {}), }; } /** * 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 ?? 3, ); const resultMsg = this.zibalService.getResultMessage(inquiryRes.result); 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, status: inquiryRes.status, statusMessage: statusMsg, result: inquiryRes.result, resultMessage: resultMsg, amount: inquiryRes.amount, refNumber: inquiryRes.refNumber, cardNumber: inquiryRes.cardNumber, paidAt: inquiryRes.paidAt, rawInquiryResponse: inquiryRes, }; } async getTransactionByTrackId(trackId: string) { return this.prisma.paymentTransaction.findFirst({ where: { trackId }, }); } async inquiryDirectZibal(trackId: string) { const inquiryRes = await this.zibalService.inquiryPayment(trackId); const statusMsg = this.zibalService.getStatusMessage( inquiryRes.status ?? 3, ); const resultMsg = this.zibalService.getResultMessage(inquiryRes.result); return { trackId, status: inquiryRes.status, statusMessage: statusMsg, result: inquiryRes.result, resultMessage: resultMsg, amount: inquiryRes.amount, refNumber: inquiryRes.refNumber, cardNumber: inquiryRes.cardNumber, paidAt: inquiryRes.paidAt, rawInquiryResponse: inquiryRes, }; } /** * 9. Admin: Manually Approve / Verify a Transaction (e.g. Card-to-Card receipt or bank transfer) */ async adminManualVerify(transactionId: string, adminNote?: string) { const transaction = await this.prisma.paymentTransaction.findUnique({ where: { id: transactionId }, include: { order: true, user: true }, }); if (!transaction) { throw new NotFoundException("تراکنش یافت نشد"); } if (transaction.status === "VERIFIED") { throw new BadRequestException("این تراکنش قبلاً تایید شده است"); } await this.prisma.$transaction(async (tx) => { await tx.paymentTransaction.update({ where: { id: transactionId }, data: { status: "VERIFIED", message: adminNote || "تایید دستی توسط مدیر سیستم (کارت به کارت / فیش بانکی)", paidAt: new Date(), }, }); if (transaction.type === "WALLET_TOPUP") { await tx.user.update({ where: { id: transaction.userId }, data: { walletBalance: { increment: Number(transaction.amount) }, }, }); await tx.walletTransaction.create({ data: { userId: transaction.userId, amount: transaction.amount, type: "deposit", status: "completed", description: `افزایش موجودی دستی تایید شده توسط ادمین (${adminNote || "کارت به کارت"})`, }, }); } else if (transaction.type === "ORDER" && transaction.orderId) { await tx.order.update({ where: { id: transaction.orderId }, data: { status: "processing", paymentMethod: "card_to_card", }, }); } }); if (transaction.type === "WALLET_TOPUP" && transaction.userId) { try { const user = await this.prisma.user.findUnique({ where: { id: transaction.userId }, }); if (user?.mobile) { const customerFullName = ( user.firstName ? `${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"), }; this.smsService .triggerEvent("WALLET_CHARGED", topupData) .catch((err) => { this.logger.warn( `Could not trigger SMS event WALLET_CHARGED: ${err}`, ); }); } } catch (err) { this.logger.warn(`Error dispatching WALLET_CHARGED SMS: ${err}`); } } return { success: true, message: "تراکنش با موفقیت به صورت دستی تایید و اعمال شد", }; } /** * 10. Admin: Manually Reject a Transaction */ async adminManualReject(transactionId: string, reason?: string) { const transaction = await this.prisma.paymentTransaction.findUnique({ where: { id: transactionId }, }); if (!transaction) { throw new NotFoundException("تراکنش یافت نشد"); } await this.prisma.paymentTransaction.update({ where: { id: transactionId }, data: { status: "FAILED", message: reason || "رد شده توسط ادمین سیستم", }, }); return { success: true, message: "تراکنش به عنوان ناموفق/رد شده علامت‌گذاری شد", }; } /** * 11. Gateway Health Check for Admin */ async checkGatewayHealth() { return this.zibalService.checkHealth(); } /** * 12. Admin: Process Gateway Refund (Zibal) with Wallet Balance Deduction if previously refunded to wallet */ async handleAdminGatewayRefund(options: { trackId: string | number; amount?: number; // Rial tryReverse?: boolean; cardNumber?: string; description?: string; orderId?: string; }) { // 1. If orderId is not passed, attempt to find by trackId let order = options.orderId ? await this.prisma.order.findUnique({ where: { id: options.orderId }, include: { user: true }, }) : null; if (!order && options.trackId) { const tx = await this.prisma.paymentTransaction.findUnique({ where: { trackId: String(options.trackId) }, include: { order: { include: { user: true } } }, }); if (tx?.order) { order = tx.order; } } if (order && order.refundStatus === "gateway") { throw new BadRequestException( "برای این سفارش قبلاً استرداد درگاه بانکی انجام شده است", ); } // 2. Execute refund via Zibal const zibalRes = await this.zibalService.requestRefund({ trackId: options.trackId, amount: options.amount, tryReverse: options.tryReverse, cardNumber: options.cardNumber, description: options.description, }); const isSuccess = zibalRes?.result === 1 || zibalRes?.status === 1 || zibalRes?.result === 100 || zibalRes?.success === true; if (isSuccess && order) { const refundAmountTomans = options.amount ? Math.round(Number(options.amount) / 10) : Number(order.totalAmount || 0); 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) { const deductionAmount = Number( order.refundedAmount || refundAmountTomans, ); await tx.user.update({ where: { id: order.userId }, data: { walletBalance: { decrement: deductionAmount }, }, }); await tx.walletTransaction.create({ data: { userId: order.userId, amount: deductionAmount, type: "withdraw", status: "completed", description: `کسر موجودی کیف پول به علت استرداد بانکی سفارش #${order.trackingNumber || order.id.slice(0, 8)} از طریق زیبال`, }, }); } // Update order refund status to gateway await tx.order.update({ where: { id: order.id }, data: { status: "cancelled", refundStatus: "gateway", refundedAmount: refundAmountTomans, refundMethod: "zibal", }, }); }); } return zibalRes; } }