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
@@ -1,78 +1,78 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString, IsNumber, IsIn } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
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 })
|
||||
@ApiPropertyOptional({ description: "شماره صفحه", default: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
page?: number = 1;
|
||||
|
||||
@ApiPropertyOptional({ description: 'تعداد در هر صفحه', default: 15 })
|
||||
@ApiPropertyOptional({ description: "تعداد در هر صفحه", default: 15 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
limit?: number = 15;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'جستجو (نام، موبایل، کد پیگیری، شماره مرجع، کد رهگیری)',
|
||||
description: "جستجو (نام، موبایل، کد پیگیری، شماره مرجع، کد رهگیری)",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
search?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'فیلتر وضعیت (VERIFIED, PENDING, FAILED)',
|
||||
description: "فیلتر وضعیت (VERIFIED, PENDING, FAILED)",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر درگاه (zibal, wallet, card)' })
|
||||
@ApiPropertyOptional({ description: "فیلتر درگاه (zibal, wallet, card)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
gateway?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'فیلتر نوع تراکنش (ORDER, WALLET_TOPUP)',
|
||||
description: "فیلتر نوع تراکنش (ORDER, WALLET_TOPUP)",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
type?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'از تاریخ (ISO format)' })
|
||||
@ApiPropertyOptional({ description: "از تاریخ (ISO format)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
startDate?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'تا تاریخ (ISO format)' })
|
||||
@ApiPropertyOptional({ description: "تا تاریخ (ISO format)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
endDate?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'حداقل مبلغ (تومان)' })
|
||||
@ApiPropertyOptional({ description: "حداقل مبلغ (تومان)" })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
minAmount?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'حداکثر مبلغ (تومان)' })
|
||||
@ApiPropertyOptional({ description: "حداکثر مبلغ (تومان)" })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
maxAmount?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلد مرتبسازی', default: 'createdAt' })
|
||||
@ApiPropertyOptional({ description: "فیلد مرتبسازی", default: "createdAt" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
sortBy?: string = 'createdAt';
|
||||
sortBy?: string = "createdAt";
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'جهت مرتبسازی (asc, desc)',
|
||||
default: 'desc',
|
||||
description: "جهت مرتبسازی (asc, desc)",
|
||||
default: "desc",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsIn(['asc', 'desc'])
|
||||
sortOrder?: 'asc' | 'desc' = 'desc';
|
||||
@IsIn(["asc", "desc"])
|
||||
sortOrder?: "asc" | "desc" = "desc";
|
||||
}
|
||||
@@ -4,51 +4,51 @@ import {
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
export class CreateEBankCheckoutDto {
|
||||
@ApiProperty({ description: 'مبلغ انتقال وجه به ریال' })
|
||||
@ApiProperty({ description: "مبلغ انتقال وجه به ریال" })
|
||||
@IsNumber()
|
||||
@Min(10000)
|
||||
amount: number;
|
||||
|
||||
@ApiProperty({ description: 'شماره شبا حساب مقصد (IR...)' })
|
||||
@ApiProperty({ description: "شماره شبا حساب مقصد (IR...)" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
iban: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه حساب مبدا پذیرنده' })
|
||||
@ApiPropertyOptional({ description: "شناسه حساب مبدا پذیرنده" })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
accountId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'کد دلیل انتقال وجه' })
|
||||
@ApiPropertyOptional({ description: "کد دلیل انتقال وجه" })
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
reasonCode?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'میزان تاخیر به دقیقه' })
|
||||
@ApiPropertyOptional({ description: "میزان تاخیر به دقیقه" })
|
||||
@IsNumber()
|
||||
@IsOptional()
|
||||
delay?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه یکتای اختصاصی' })
|
||||
@ApiPropertyOptional({ description: "شناسه یکتای اختصاصی" })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
uniqueCode?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'توضیحات انتقال وجه' })
|
||||
@ApiPropertyOptional({ description: "توضیحات انتقال وجه" })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه واریز' })
|
||||
@ApiPropertyOptional({ description: "شناسه واریز" })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
paymentNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس کالبک وبهوک' })
|
||||
@ApiPropertyOptional({ description: "آدرس کالبک وبهوک" })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
callbackUrl?: string;
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class InitiatePaymentDto {
|
||||
@ApiProperty({ description: 'شناسه سفارش در دیتابیس' })
|
||||
@ApiProperty({ description: "شناسه سفارش در دیتابیس" })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
orderId: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس بازگشت اختیاری جهت سفارشیسازی' })
|
||||
@ApiPropertyOptional({ description: "آدرس بازگشت اختیاری جهت سفارشیسازی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
customCallbackUrl?: string;
|
||||
}
|
||||
|
||||
export class InitiateWalletTopupDto {
|
||||
@ApiProperty({ description: 'مبلغ افزایش اعتبار (به تومان)' })
|
||||
@ApiProperty({ description: "مبلغ افزایش اعتبار (به تومان)" })
|
||||
@IsNotEmpty()
|
||||
amount: number;
|
||||
|
||||
@ApiPropertyOptional({ description: 'آدرس بازگشت اختیاری' })
|
||||
@ApiPropertyOptional({ description: "آدرس بازگشت اختیاری" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
customCallbackUrl?: string;
|
||||
|
||||
@@ -1,48 +1,48 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class ZibalCallbackQueryDto {
|
||||
@ApiPropertyOptional({ description: 'وضعیت موفقیت اولیه زیبال (1 یا 0)' })
|
||||
@ApiPropertyOptional({ description: "وضعیت موفقیت اولیه زیبال (1 یا 0)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
success?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه پیگیری تراکنش زیبال' })
|
||||
@ApiPropertyOptional({ description: "شناسه پیگیری تراکنش زیبال" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
trackId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه سفارش ارسال شده در زمان ایجاد' })
|
||||
@ApiPropertyOptional({ description: "شناسه سفارش ارسال شده در زمان ایجاد" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
orderId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'کد وضعیت پرداخت زیبال' })
|
||||
@ApiPropertyOptional({ description: "کد وضعیت پرداخت زیبال" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شماره کارت ماسک شده (در متد لِیزی)' })
|
||||
@ApiPropertyOptional({ description: "شماره کارت ماسک شده (در متد لِیزی)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cardNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شماره کارت هش شده (در متد لِیزی)' })
|
||||
@ApiPropertyOptional({ description: "شماره کارت هش شده (در متد لِیزی)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
hashedCardNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'نوع پرداخت (ORDER یا WALLET_TOPUP)' })
|
||||
@ApiPropertyOptional({ description: "نوع پرداخت (ORDER یا WALLET_TOPUP)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
type?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'مبلغ تراکنش' })
|
||||
@ApiPropertyOptional({ description: "مبلغ تراکنش" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
amount?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'پیام تراکنش' })
|
||||
@ApiPropertyOptional({ description: "پیام تراکنش" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
message?: string;
|
||||
|
||||
@@ -34,7 +34,7 @@ export interface PaymentInquiryResult {
|
||||
|
||||
export interface GatewayHealthResult {
|
||||
gatewayName: string;
|
||||
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
|
||||
status: "ONLINE" | "DEGRADED" | "OFFLINE";
|
||||
latencyMs: number;
|
||||
merchantConfigured: boolean;
|
||||
activeMerchant: string;
|
||||
|
||||
@@ -0,0 +1,841 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { PaymentController } from "./payment.controller";
|
||||
import { PaymentService } from "./payment.service";
|
||||
import { ZibalService } from "./zibal.service";
|
||||
import { ZibalEBankService } from "./zibal-ebank.service";
|
||||
import { BadRequestException, HttpStatus } from "@nestjs/common";
|
||||
import type { Request, Response } from "express";
|
||||
|
||||
describe("PaymentController", () => {
|
||||
let controller: PaymentController;
|
||||
let paymentService: PaymentService;
|
||||
let zibalService: ZibalService;
|
||||
let zibalEBankService: ZibalEBankService;
|
||||
|
||||
const mockPaymentService = {
|
||||
initiateOrderPayment: jest.fn(),
|
||||
initiateWalletTopup: jest.fn(),
|
||||
verifyAndProcess: jest.fn(),
|
||||
getTransaction: jest.fn(),
|
||||
handleAdminGatewayRefund: jest.fn(),
|
||||
getAdminTransactions: jest.fn(),
|
||||
getAdminTransactionStats: jest.fn(),
|
||||
reconcilePendingTransactions: jest.fn(),
|
||||
adminLiveInquiry: jest.fn(),
|
||||
getTransactionByTrackId: jest.fn(),
|
||||
inquiryDirectZibal: jest.fn(),
|
||||
adminManualVerify: jest.fn(),
|
||||
adminManualReject: jest.fn(),
|
||||
checkGatewayHealth: jest.fn(),
|
||||
};
|
||||
|
||||
const mockZibalService = {
|
||||
getFrontendUrl: jest.fn(),
|
||||
getWalletList: jest.fn(),
|
||||
inquireRefund: jest.fn(),
|
||||
getRefundList: jest.fn(),
|
||||
getGatewayTransactionsReport: jest.fn(),
|
||||
getCheckoutReport: jest.fn(),
|
||||
getCheckoutQueueReport: jest.fn(),
|
||||
getSubMerchantList: jest.fn(),
|
||||
createSubMerchant: jest.fn(),
|
||||
editSubMerchant: jest.fn(),
|
||||
};
|
||||
|
||||
const mockZibalEBankService = {
|
||||
getAccountList: jest.fn(),
|
||||
getAccountBalance: jest.fn(),
|
||||
getStatementList: jest.fn(),
|
||||
createCheckout: jest.fn(),
|
||||
getCheckoutList: jest.fn(),
|
||||
cancelCheckout: jest.fn(),
|
||||
getIdentifiedPaymentList: jest.fn(),
|
||||
changeIdentifiedPaymentStatus: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [PaymentController],
|
||||
providers: [
|
||||
{
|
||||
provide: PaymentService,
|
||||
useValue: mockPaymentService,
|
||||
},
|
||||
{
|
||||
provide: ZibalService,
|
||||
useValue: mockZibalService,
|
||||
},
|
||||
{
|
||||
provide: ZibalEBankService,
|
||||
useValue: mockZibalEBankService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<PaymentController>(PaymentController);
|
||||
paymentService = module.get<PaymentService>(PaymentService);
|
||||
zibalService = module.get<ZibalService>(ZibalService);
|
||||
zibalEBankService = module.get<ZibalEBankService>(ZibalEBankService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(controller).toBeDefined();
|
||||
expect(paymentService).toBeDefined();
|
||||
expect(zibalService).toBeDefined();
|
||||
expect(zibalEBankService).toBeDefined();
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// Public & User Payment Endpoints
|
||||
// ==========================================
|
||||
describe("initiateOrderPayment", () => {
|
||||
it("should initiate order payment with extracted client IP and user-agent", async () => {
|
||||
const mockReq = {
|
||||
headers: { "x-forwarded-for": "185.190.150.1, 10.0.0.1" },
|
||||
user: { id: "user-123" },
|
||||
} as unknown as Request & { user: { id: string } };
|
||||
|
||||
const body = {
|
||||
orderId: "order-456",
|
||||
customCallbackUrl: "https://canina.ir/custom-callback",
|
||||
};
|
||||
|
||||
const mockResponse = {
|
||||
trackId: 10001,
|
||||
paymentUrl: "https://gateway.zibal.ir/start/10001",
|
||||
result: 100,
|
||||
message: "success",
|
||||
};
|
||||
|
||||
mockPaymentService.initiateOrderPayment.mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await controller.initiateOrderPayment(
|
||||
mockReq,
|
||||
body,
|
||||
"127.0.0.1",
|
||||
"Mozilla/5.0 Chrome",
|
||||
);
|
||||
|
||||
expect(paymentService.initiateOrderPayment).toHaveBeenCalledWith(
|
||||
"user-123",
|
||||
"order-456",
|
||||
"https://canina.ir/custom-callback",
|
||||
{ ipAddress: "185.190.150.1", userAgent: "Mozilla/5.0 Chrome" },
|
||||
);
|
||||
expect(result).toEqual(mockResponse);
|
||||
});
|
||||
|
||||
it("should fall back to req.ip or fallbackIp when forwarded headers are missing", async () => {
|
||||
const mockReq = {
|
||||
headers: {},
|
||||
ip: "::ffff:192.168.1.50",
|
||||
user: { id: "user-123" },
|
||||
} as unknown as Request & { user: { id: string } };
|
||||
|
||||
const body = { orderId: "order-999" };
|
||||
mockPaymentService.initiateOrderPayment.mockResolvedValue({
|
||||
trackId: 20002,
|
||||
});
|
||||
|
||||
await controller.initiateOrderPayment(mockReq, body, "10.0.0.5");
|
||||
|
||||
expect(paymentService.initiateOrderPayment).toHaveBeenCalledWith(
|
||||
"user-123",
|
||||
"order-999",
|
||||
undefined,
|
||||
{ ipAddress: "10.0.0.5", userAgent: undefined },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("initiateWalletTopup", () => {
|
||||
it("should initiate wallet recharge with numeric amount", async () => {
|
||||
const mockReq = {
|
||||
headers: { "x-real-ip": "91.98.10.20" },
|
||||
user: { id: "user-456" },
|
||||
} as unknown as Request & { user: { id: string } };
|
||||
|
||||
const body = {
|
||||
amount: 5000000,
|
||||
customCallbackUrl: "https://canina.ir/wallet",
|
||||
};
|
||||
|
||||
mockPaymentService.initiateWalletTopup.mockResolvedValue({
|
||||
trackId: 30003,
|
||||
paymentUrl: "https://gateway.zibal.ir/start/30003",
|
||||
});
|
||||
|
||||
const result = await controller.initiateWalletTopup(
|
||||
mockReq,
|
||||
body,
|
||||
"127.0.0.1",
|
||||
"Safari",
|
||||
);
|
||||
|
||||
expect(paymentService.initiateWalletTopup).toHaveBeenCalledWith(
|
||||
"user-456",
|
||||
5000000,
|
||||
"https://canina.ir/wallet",
|
||||
{ ipAddress: "91.98.10.20", userAgent: "Safari" },
|
||||
);
|
||||
expect(result.trackId).toBe(30003);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleZibalCallback", () => {
|
||||
it("should redirect with error when trackId is missing", async () => {
|
||||
mockZibalService.getFrontendUrl.mockResolvedValue("https://canina.ir");
|
||||
|
||||
const mockReq = { headers: {} } as unknown as Request;
|
||||
const mockRes = { redirect: jest.fn() } as unknown as Response;
|
||||
|
||||
await controller.handleZibalCallback(
|
||||
mockReq,
|
||||
{ trackId: "", success: "0" },
|
||||
mockRes,
|
||||
"127.0.0.1",
|
||||
);
|
||||
|
||||
expect(mockRes.redirect).toHaveBeenCalledWith(
|
||||
expect.stringContaining("https://canina.ir/payment/verify?success=0"),
|
||||
);
|
||||
});
|
||||
|
||||
it("should process payment verification and redirect with query params on success", async () => {
|
||||
mockZibalService.getFrontendUrl.mockResolvedValue("https://canina.ir");
|
||||
|
||||
const mockReq = {
|
||||
headers: { "x-real-ip": "185.190.150.1" },
|
||||
} as unknown as Request;
|
||||
const mockRes = { redirect: jest.fn() } as unknown as Response;
|
||||
|
||||
mockPaymentService.verifyAndProcess.mockResolvedValue({
|
||||
trackId: "12345",
|
||||
success: true,
|
||||
status: "2",
|
||||
orderId: "order-777",
|
||||
refNumber: "REF-9988",
|
||||
cardNumber: "6037********1234",
|
||||
message: "پرداخت موفق",
|
||||
amount: 1500000,
|
||||
type: "ORDER",
|
||||
});
|
||||
|
||||
await controller.handleZibalCallback(
|
||||
mockReq,
|
||||
{
|
||||
trackId: "12345",
|
||||
success: "1",
|
||||
status: "2",
|
||||
orderId: "order-777",
|
||||
},
|
||||
mockRes,
|
||||
"127.0.0.1",
|
||||
"Mozilla",
|
||||
);
|
||||
|
||||
expect(paymentService.verifyAndProcess).toHaveBeenCalledWith(
|
||||
"12345",
|
||||
"1",
|
||||
"2",
|
||||
"order-777",
|
||||
{ ipAddress: "185.190.150.1", userAgent: "Mozilla" },
|
||||
);
|
||||
|
||||
expect(mockRes.redirect).toHaveBeenCalledWith(
|
||||
expect.stringMatching(
|
||||
/https:\/\/canina\.ir\/payment\/verify\?.*trackId=12345.*success=1/,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("should redirect to error verify page if verifyAndProcess throws", async () => {
|
||||
mockZibalService.getFrontendUrl.mockResolvedValue("https://canina.ir");
|
||||
|
||||
const mockReq = { headers: {} } as unknown as Request;
|
||||
const mockRes = { redirect: jest.fn() } as unknown as Response;
|
||||
|
||||
mockPaymentService.verifyAndProcess.mockRejectedValue(
|
||||
new Error("کد امنیتی یا مبلغ نامعتبر است"),
|
||||
);
|
||||
|
||||
await controller.handleZibalCallback(
|
||||
mockReq,
|
||||
{ trackId: "99999", success: "0" },
|
||||
mockRes,
|
||||
"127.0.0.1",
|
||||
);
|
||||
|
||||
expect(mockRes.redirect).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
"https://canina.ir/payment/verify?success=0&trackId=99999",
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyPaymentDirect", () => {
|
||||
it("should throw BadRequestException if trackId is missing", async () => {
|
||||
await expect(
|
||||
controller.verifyPaymentDirect("", "1", "2"),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("should verify directly and return verify result", async () => {
|
||||
const verifyResult = {
|
||||
success: true,
|
||||
status: 1,
|
||||
refNumber: "12345678",
|
||||
orderId: "ord-1",
|
||||
};
|
||||
|
||||
mockPaymentService.verifyAndProcess.mockResolvedValue(verifyResult);
|
||||
|
||||
const result = await controller.verifyPaymentDirect(
|
||||
"track-1",
|
||||
"1",
|
||||
"2",
|
||||
"ord-1",
|
||||
"127.0.0.1",
|
||||
"Chrome",
|
||||
);
|
||||
|
||||
expect(paymentService.verifyAndProcess).toHaveBeenCalledWith(
|
||||
"track-1",
|
||||
"1",
|
||||
"2",
|
||||
"ord-1",
|
||||
{ ipAddress: "127.0.0.1", userAgent: "Chrome" },
|
||||
);
|
||||
expect(result).toEqual(verifyResult);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleZibalLazyCallback", () => {
|
||||
it("should return BAD_REQUEST if trackId is missing in body", async () => {
|
||||
const jsonMock = jest.fn();
|
||||
const statusMock = jest.fn().mockReturnValue({ json: jsonMock });
|
||||
const mockRes = { status: statusMock } as unknown as Response;
|
||||
|
||||
await controller.handleZibalLazyCallback(
|
||||
{ trackId: "" },
|
||||
mockRes,
|
||||
"127.0.0.1",
|
||||
);
|
||||
|
||||
expect(statusMock).toHaveBeenCalledWith(HttpStatus.BAD_REQUEST);
|
||||
expect(jsonMock).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: "trackId is required",
|
||||
});
|
||||
});
|
||||
|
||||
it("should process webhook callback and return HTTP 200 with result", async () => {
|
||||
const jsonMock = jest.fn();
|
||||
const statusMock = jest.fn().mockReturnValue({ json: jsonMock });
|
||||
const mockRes = { status: statusMock } as unknown as Response;
|
||||
|
||||
const verifyResult = { success: true, trackId: "98765" };
|
||||
mockPaymentService.verifyAndProcess.mockResolvedValue(verifyResult);
|
||||
|
||||
await controller.handleZibalLazyCallback(
|
||||
{
|
||||
trackId: "98765",
|
||||
success: "1",
|
||||
status: "2",
|
||||
orderId: "ord-2",
|
||||
},
|
||||
mockRes,
|
||||
"127.0.0.1",
|
||||
"ZibalBot",
|
||||
);
|
||||
|
||||
expect(paymentService.verifyAndProcess).toHaveBeenCalledWith(
|
||||
"98765",
|
||||
"1",
|
||||
"2",
|
||||
"ord-2",
|
||||
{ ipAddress: "127.0.0.1", userAgent: "ZibalBot" },
|
||||
);
|
||||
expect(statusMock).toHaveBeenCalledWith(HttpStatus.OK);
|
||||
expect(jsonMock).toHaveBeenCalledWith(verifyResult);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTransactionStatus", () => {
|
||||
it("should retrieve status passing isAdmin correctly for Admin user", async () => {
|
||||
const mockReq = { user: { id: "admin-1", role: "Admin" } };
|
||||
mockPaymentService.getTransaction.mockResolvedValue({
|
||||
id: "tx-1",
|
||||
status: "PAID",
|
||||
});
|
||||
|
||||
const result = await controller.getTransactionStatus(
|
||||
mockReq,
|
||||
"track-100",
|
||||
);
|
||||
|
||||
expect(paymentService.getTransaction).toHaveBeenCalledWith(
|
||||
"track-100",
|
||||
"admin-1",
|
||||
true,
|
||||
);
|
||||
expect(result).toEqual({ id: "tx-1", status: "PAID" });
|
||||
});
|
||||
|
||||
it("should retrieve status with isAdmin=false for regular user", async () => {
|
||||
const mockReq = { user: { id: "user-1", role: "User" } };
|
||||
mockPaymentService.getTransaction.mockResolvedValue({
|
||||
id: "tx-2",
|
||||
status: "PENDING",
|
||||
});
|
||||
|
||||
const result = await controller.getTransactionStatus(
|
||||
mockReq,
|
||||
"track-200",
|
||||
);
|
||||
|
||||
expect(paymentService.getTransaction).toHaveBeenCalledWith(
|
||||
"track-200",
|
||||
"user-1",
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual({ id: "tx-2", status: "PENDING" });
|
||||
});
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// Admin Gateway, Wallets & Refunds
|
||||
// ==========================================
|
||||
describe("Admin Wallets & Refunds", () => {
|
||||
it("should get admin wallets", async () => {
|
||||
mockZibalService.getWalletList.mockResolvedValue([
|
||||
{ walletId: "main", balance: 50000000 },
|
||||
]);
|
||||
|
||||
const result = await controller.getAdminWallets();
|
||||
|
||||
expect(zibalService.getWalletList).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual([{ walletId: "main", balance: 50000000 }]);
|
||||
});
|
||||
|
||||
it("should create refund", async () => {
|
||||
const refundBody = {
|
||||
trackId: "123",
|
||||
amount: 100000,
|
||||
description: "کسر موجودی",
|
||||
};
|
||||
mockPaymentService.handleAdminGatewayRefund.mockResolvedValue({
|
||||
success: true,
|
||||
});
|
||||
|
||||
const result = await controller.createRefund(refundBody);
|
||||
|
||||
expect(paymentService.handleAdminGatewayRefund).toHaveBeenCalledWith(
|
||||
refundBody,
|
||||
);
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
|
||||
it("should inquire refund status", async () => {
|
||||
const body = { refundId: "ref-10" };
|
||||
mockZibalService.inquireRefund.mockResolvedValue({ status: 1 });
|
||||
|
||||
const result = await controller.inquireRefund(body);
|
||||
|
||||
expect(zibalService.inquireRefund).toHaveBeenCalledWith(body);
|
||||
expect(result).toEqual({ status: 1 });
|
||||
});
|
||||
|
||||
it("should get refund list", async () => {
|
||||
const filter = { page: 1, size: 10 };
|
||||
mockZibalService.getRefundList.mockResolvedValue({ list: [], total: 0 });
|
||||
|
||||
const result = await controller.getRefundList(filter);
|
||||
|
||||
expect(zibalService.getRefundList).toHaveBeenCalledWith(filter);
|
||||
expect(result).toEqual({ list: [], total: 0 });
|
||||
});
|
||||
|
||||
it("should get gateway transaction report", async () => {
|
||||
const filter = { page: 1, size: 20, trackId: 100 };
|
||||
mockZibalService.getGatewayTransactionsReport.mockResolvedValue({
|
||||
total: 1,
|
||||
});
|
||||
|
||||
const result = await controller.getGatewayReport(filter);
|
||||
|
||||
expect(zibalService.getGatewayTransactionsReport).toHaveBeenCalledWith(
|
||||
filter,
|
||||
);
|
||||
expect(result).toEqual({ total: 1 });
|
||||
});
|
||||
|
||||
it("should get checkout report", async () => {
|
||||
const filter = { page: 1, size: 20 };
|
||||
mockZibalService.getCheckoutReport.mockResolvedValue({ list: [] });
|
||||
|
||||
const result = await controller.getCheckoutReport(filter);
|
||||
|
||||
expect(zibalService.getCheckoutReport).toHaveBeenCalledWith(filter);
|
||||
expect(result).toEqual({ list: [] });
|
||||
});
|
||||
|
||||
it("should get checkout queue report", async () => {
|
||||
mockZibalService.getCheckoutQueueReport.mockResolvedValue({
|
||||
inQueueCount: 3,
|
||||
});
|
||||
|
||||
const result = await controller.getCheckoutQueueReport();
|
||||
|
||||
expect(zibalService.getCheckoutQueueReport).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({ inQueueCount: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// Admin Sub-Merchants
|
||||
// ==========================================
|
||||
describe("Admin Sub-Merchants", () => {
|
||||
it("should get sub-merchants with default and custom pagination", async () => {
|
||||
mockZibalService.getSubMerchantList.mockResolvedValue({ list: [] });
|
||||
|
||||
await controller.getSubMerchants();
|
||||
expect(zibalService.getSubMerchantList).toHaveBeenCalledWith(1, 20);
|
||||
|
||||
await controller.getSubMerchants("2", "50");
|
||||
expect(zibalService.getSubMerchantList).toHaveBeenCalledWith(2, 50);
|
||||
});
|
||||
|
||||
it("should create sub-merchant", async () => {
|
||||
const body = { bankAccount: "IR123456789", name: "دامپزشکی تهران" };
|
||||
mockZibalService.createSubMerchant.mockResolvedValue({ id: "sub-1" });
|
||||
|
||||
const result = await controller.createSubMerchant(body);
|
||||
|
||||
expect(zibalService.createSubMerchant).toHaveBeenCalledWith(body);
|
||||
expect(result).toEqual({ id: "sub-1" });
|
||||
});
|
||||
|
||||
it("should edit sub-merchant", async () => {
|
||||
const body = {
|
||||
id: "sub-1",
|
||||
bankAccount: "IR987654321",
|
||||
name: "نام جدید",
|
||||
};
|
||||
mockZibalService.editSubMerchant.mockResolvedValue({ success: true });
|
||||
|
||||
const result = await controller.editSubMerchant(body);
|
||||
|
||||
expect(zibalService.editSubMerchant).toHaveBeenCalledWith(body);
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// Admin Corporate Banking (EBank)
|
||||
// ==========================================
|
||||
describe("Admin EBank", () => {
|
||||
it("should get ebank accounts", async () => {
|
||||
mockZibalEBankService.getAccountList.mockResolvedValue([{ id: "acc-1" }]);
|
||||
|
||||
await controller.getEBankAccounts("true");
|
||||
expect(zibalEBankService.getAccountList).toHaveBeenCalledWith(true);
|
||||
|
||||
await controller.getEBankAccounts("false");
|
||||
expect(zibalEBankService.getAccountList).toHaveBeenCalledWith(false);
|
||||
|
||||
await controller.getEBankAccounts(undefined);
|
||||
expect(zibalEBankService.getAccountList).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it("should get ebank balance", async () => {
|
||||
mockZibalEBankService.getAccountBalance.mockResolvedValue({
|
||||
balance: 10000000,
|
||||
});
|
||||
|
||||
const result = await controller.getEBankBalance("acc-1", "true");
|
||||
|
||||
expect(zibalEBankService.getAccountBalance).toHaveBeenCalledWith(
|
||||
"acc-1",
|
||||
true,
|
||||
);
|
||||
expect(result).toEqual({ balance: 10000000 });
|
||||
});
|
||||
|
||||
it("should get ebank statements", async () => {
|
||||
mockZibalEBankService.getStatementList.mockResolvedValue({
|
||||
statements: [],
|
||||
});
|
||||
|
||||
const result = await controller.getEBankStatements(
|
||||
"acc-1",
|
||||
"2026-01-01",
|
||||
"2026-01-10",
|
||||
"true",
|
||||
"15",
|
||||
"2",
|
||||
);
|
||||
|
||||
expect(zibalEBankService.getStatementList).toHaveBeenCalledWith({
|
||||
accountId: "acc-1",
|
||||
fromDate: "2026-01-01",
|
||||
toDate: "2026-01-10",
|
||||
update: true,
|
||||
size: 15,
|
||||
page: 2,
|
||||
});
|
||||
expect(result).toEqual({ statements: [] });
|
||||
});
|
||||
|
||||
it("should create ebank checkout", async () => {
|
||||
const body = {
|
||||
amount: 2000000,
|
||||
destinationIban: "IR0000000000",
|
||||
destinationFirstName: "علی",
|
||||
destinationLastName: "اکبری",
|
||||
};
|
||||
mockZibalEBankService.createCheckout.mockResolvedValue({
|
||||
checkoutId: "chk-1",
|
||||
});
|
||||
|
||||
const result = await controller.createEBankCheckout(body as any);
|
||||
|
||||
expect(zibalEBankService.createCheckout).toHaveBeenCalledWith(body);
|
||||
expect(result).toEqual({ checkoutId: "chk-1" });
|
||||
});
|
||||
|
||||
it("should get ebank checkout list", async () => {
|
||||
mockZibalEBankService.getCheckoutList.mockResolvedValue({
|
||||
checkouts: [],
|
||||
});
|
||||
|
||||
await controller.getEBankCheckoutList(
|
||||
"acc-1",
|
||||
"2026-01-01",
|
||||
"2026-01-10",
|
||||
"1",
|
||||
"25",
|
||||
"3",
|
||||
);
|
||||
|
||||
expect(zibalEBankService.getCheckoutList).toHaveBeenCalledWith({
|
||||
accountId: "acc-1",
|
||||
fromDate: "2026-01-01",
|
||||
toDate: "2026-01-10",
|
||||
status: 1,
|
||||
size: 25,
|
||||
page: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("should cancel ebank checkout", async () => {
|
||||
const body = { checkoutIds: ["chk-1", "chk-2"], accountId: "acc-1" };
|
||||
mockZibalEBankService.cancelCheckout.mockResolvedValue({ cancelled: 2 });
|
||||
|
||||
const result = await controller.cancelEBankCheckout(body);
|
||||
|
||||
expect(zibalEBankService.cancelCheckout).toHaveBeenCalledWith(
|
||||
["chk-1", "chk-2"],
|
||||
"acc-1",
|
||||
);
|
||||
expect(result).toEqual({ cancelled: 2 });
|
||||
});
|
||||
|
||||
it("should get identified payments", async () => {
|
||||
mockZibalEBankService.getIdentifiedPaymentList.mockResolvedValue({
|
||||
items: [],
|
||||
});
|
||||
|
||||
await controller.getEBankIdentifiedPayments(
|
||||
"acc-1",
|
||||
"2026-01-01",
|
||||
"2026-01-10",
|
||||
"2",
|
||||
"10",
|
||||
"1",
|
||||
);
|
||||
|
||||
expect(zibalEBankService.getIdentifiedPaymentList).toHaveBeenCalledWith({
|
||||
accountId: "acc-1",
|
||||
fromDate: "2026-01-01",
|
||||
toDate: "2026-01-10",
|
||||
status: 2,
|
||||
size: 10,
|
||||
page: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("should change identified payment status", async () => {
|
||||
const body = {
|
||||
transactionId: "txn-1",
|
||||
status: 2 as const,
|
||||
accountId: "acc-1",
|
||||
};
|
||||
mockZibalEBankService.changeIdentifiedPaymentStatus.mockResolvedValue({
|
||||
success: true,
|
||||
});
|
||||
|
||||
const result = await controller.changeIdentifiedPaymentStatus(body);
|
||||
|
||||
expect(
|
||||
zibalEBankService.changeIdentifiedPaymentStatus,
|
||||
).toHaveBeenCalledWith("txn-1", 2, "acc-1");
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// Admin Transaction Logs, Reconcile, Inquiry & Diagnostics
|
||||
// ==========================================
|
||||
describe("Admin Transactions & Diagnostics", () => {
|
||||
it("should get admin transactions", async () => {
|
||||
const filter = { page: 1, limit: 10 };
|
||||
mockPaymentService.getAdminTransactions.mockResolvedValue({
|
||||
data: [],
|
||||
total: 0,
|
||||
});
|
||||
|
||||
const result = await controller.getAdminTransactions(filter);
|
||||
|
||||
expect(paymentService.getAdminTransactions).toHaveBeenCalledWith(filter);
|
||||
expect(result).toEqual({ data: [], total: 0 });
|
||||
});
|
||||
|
||||
it("should get admin stats", async () => {
|
||||
mockPaymentService.getAdminTransactionStats.mockResolvedValue({
|
||||
totalVolume: 1000000,
|
||||
});
|
||||
|
||||
const result = await controller.getAdminStats();
|
||||
|
||||
expect(paymentService.getAdminTransactionStats).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({ totalVolume: 1000000 });
|
||||
});
|
||||
|
||||
it("should reconcile pending transactions", async () => {
|
||||
mockPaymentService.reconcilePendingTransactions.mockResolvedValue({
|
||||
reconciled: 5,
|
||||
});
|
||||
|
||||
const result = await controller.reconcilePending();
|
||||
|
||||
expect(paymentService.reconcilePendingTransactions).toHaveBeenCalledTimes(
|
||||
1,
|
||||
);
|
||||
expect(result).toEqual({ reconciled: 5 });
|
||||
});
|
||||
|
||||
describe("liveInquiryPost", () => {
|
||||
it("should inquire by transactionId if provided", async () => {
|
||||
mockPaymentService.adminLiveInquiry.mockResolvedValue({
|
||||
status: "PAID",
|
||||
});
|
||||
|
||||
const result = await controller.liveInquiryPost({
|
||||
transactionId: "txn-100",
|
||||
});
|
||||
|
||||
expect(paymentService.adminLiveInquiry).toHaveBeenCalledWith("txn-100");
|
||||
expect(result).toEqual({ status: "PAID" });
|
||||
});
|
||||
|
||||
it("should inquire by trackId when tx record exists in database", async () => {
|
||||
mockPaymentService.getTransactionByTrackId.mockResolvedValue({
|
||||
id: "txn-found",
|
||||
});
|
||||
mockPaymentService.adminLiveInquiry.mockResolvedValue({
|
||||
status: "PAID",
|
||||
});
|
||||
|
||||
const result = await controller.liveInquiryPost({ trackId: "9988" });
|
||||
|
||||
expect(paymentService.getTransactionByTrackId).toHaveBeenCalledWith(
|
||||
"9988",
|
||||
);
|
||||
expect(paymentService.adminLiveInquiry).toHaveBeenCalledWith(
|
||||
"txn-found",
|
||||
);
|
||||
expect(result).toEqual({ status: "PAID" });
|
||||
});
|
||||
|
||||
it("should fallback to direct Zibal inquiry when trackId has no local tx record", async () => {
|
||||
mockPaymentService.getTransactionByTrackId.mockResolvedValue(null);
|
||||
mockPaymentService.inquiryDirectZibal.mockResolvedValue({ status: 1 });
|
||||
|
||||
const result = await controller.liveInquiryPost({ trackId: "4455" });
|
||||
|
||||
expect(paymentService.getTransactionByTrackId).toHaveBeenCalledWith(
|
||||
"4455",
|
||||
);
|
||||
expect(paymentService.inquiryDirectZibal).toHaveBeenCalledWith("4455");
|
||||
expect(result).toEqual({ status: 1 });
|
||||
});
|
||||
|
||||
it("should throw BadRequestException if neither transactionId nor trackId is provided", async () => {
|
||||
await expect(controller.liveInquiryPost({})).rejects.toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should perform live inquiry by param id", async () => {
|
||||
mockPaymentService.adminLiveInquiry.mockResolvedValue({
|
||||
status: "VERIFIED",
|
||||
});
|
||||
|
||||
const result = await controller.liveInquiry("txn-300");
|
||||
|
||||
expect(paymentService.adminLiveInquiry).toHaveBeenCalledWith("txn-300");
|
||||
expect(result).toEqual({ status: "VERIFIED" });
|
||||
});
|
||||
|
||||
it("should manually verify payment", async () => {
|
||||
mockPaymentService.adminManualVerify.mockResolvedValue({
|
||||
status: "MANUALLY_VERIFIED",
|
||||
});
|
||||
|
||||
const result = await controller.manualVerify("txn-1", {
|
||||
adminNote: "واریز کارت تایید شد",
|
||||
});
|
||||
|
||||
expect(paymentService.adminManualVerify).toHaveBeenCalledWith(
|
||||
"txn-1",
|
||||
"واریز کارت تایید شد",
|
||||
);
|
||||
expect(result).toEqual({ status: "MANUALLY_VERIFIED" });
|
||||
});
|
||||
|
||||
it("should manually reject payment", async () => {
|
||||
mockPaymentService.adminManualReject.mockResolvedValue({
|
||||
status: "REJECTED",
|
||||
});
|
||||
|
||||
const result = await controller.manualReject("txn-1", {
|
||||
reason: "فیش جعلی",
|
||||
});
|
||||
|
||||
expect(paymentService.adminManualReject).toHaveBeenCalledWith(
|
||||
"txn-1",
|
||||
"فیش جعلی",
|
||||
);
|
||||
expect(result).toEqual({ status: "REJECTED" });
|
||||
});
|
||||
|
||||
it("should check gateway health", async () => {
|
||||
mockPaymentService.checkGatewayHealth.mockResolvedValue({
|
||||
healthy: true,
|
||||
latencyMs: 45,
|
||||
});
|
||||
|
||||
const result = await controller.getHealth();
|
||||
|
||||
expect(paymentService.checkGatewayHealth).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({ healthy: true, latencyMs: 45 });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -13,31 +13,31 @@ import {
|
||||
Headers,
|
||||
Ip,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { ZibalEBankService } from './zibal-ebank.service';
|
||||
import { CreateEBankCheckoutDto } from './dto/ebank-checkout.dto';
|
||||
} from "@nestjs/common";
|
||||
import type { Request, Response } from "express";
|
||||
import { PaymentService } from "./payment.service";
|
||||
import { ZibalService } from "./zibal.service";
|
||||
import { ZibalEBankService } from "./zibal-ebank.service";
|
||||
import { CreateEBankCheckoutDto } from "./dto/ebank-checkout.dto";
|
||||
import {
|
||||
InitiatePaymentDto,
|
||||
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';
|
||||
} 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,
|
||||
ApiBearerAuth,
|
||||
ApiOkResponse,
|
||||
ApiBadRequestResponse,
|
||||
} from '@nestjs/swagger';
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
@ApiTags('Payment - درگاه پرداخت اینترنتی زیبال و مدیریت تراکنشها')
|
||||
@Controller('payment')
|
||||
@ApiTags("Payment - درگاه پرداخت اینترنتی زیبال و مدیریت تراکنشها")
|
||||
@Controller("payment")
|
||||
export class PaymentController {
|
||||
constructor(
|
||||
private readonly paymentService: PaymentService,
|
||||
@@ -46,37 +46,37 @@ export class PaymentController {
|
||||
) {}
|
||||
|
||||
private extractRealClientIp(req: Request, fallbackIp?: string): string {
|
||||
const xForwardedFor = req.headers['x-forwarded-for'];
|
||||
const xForwardedFor = req.headers["x-forwarded-for"];
|
||||
if (xForwardedFor) {
|
||||
const forwardedIps = Array.isArray(xForwardedFor)
|
||||
? xForwardedFor[0]
|
||||
: xForwardedFor.split(',')[0];
|
||||
: xForwardedFor.split(",")[0];
|
||||
if (forwardedIps && forwardedIps.trim()) {
|
||||
return forwardedIps.trim().replace(/^::ffff:/, '');
|
||||
return forwardedIps.trim().replace(/^::ffff:/, "");
|
||||
}
|
||||
}
|
||||
const xRealIp = req.headers['x-real-ip'];
|
||||
if (xRealIp && typeof xRealIp === 'string') {
|
||||
return xRealIp.trim().replace(/^::ffff:/, '');
|
||||
const xRealIp = req.headers["x-real-ip"];
|
||||
if (xRealIp && typeof xRealIp === "string") {
|
||||
return xRealIp.trim().replace(/^::ffff:/, "");
|
||||
}
|
||||
return (fallbackIp || req.ip || '').replace(/^::ffff:/, '');
|
||||
return (fallbackIp || req.ip || "").replace(/^::ffff:/, "");
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('zibal/initiate')
|
||||
@ApiOperation({ summary: 'شروع فرایند پرداخت آنلاین سفارش با درگاه زیبال' })
|
||||
@Post("zibal/initiate")
|
||||
@ApiOperation({ summary: "شروع فرایند پرداخت آنلاین سفارش با درگاه زیبال" })
|
||||
@ApiOkResponse({
|
||||
description: 'لینک هدایت به درگاه پرداخت زیبال با موفقیت تولید شد',
|
||||
description: "لینک هدایت به درگاه پرداخت زیبال با موفقیت تولید شد",
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'خطا در ایجاد تراکنش یا نامعتبر بودن سفارش',
|
||||
description: "خطا در ایجاد تراکنش یا نامعتبر بودن سفارش",
|
||||
})
|
||||
async initiateOrderPayment(
|
||||
@Req() req: Request & { user: { id: string } },
|
||||
@Body() body: InitiatePaymentDto,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
@Headers("user-agent") userAgent?: string,
|
||||
) {
|
||||
const realIp = this.extractRealClientIp(req, ip);
|
||||
return this.paymentService.initiateOrderPayment(
|
||||
@@ -89,16 +89,16 @@ export class PaymentController {
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('zibal/wallet/initiate')
|
||||
@ApiOperation({ summary: 'شارژ آنلاین کیف پول از طریق درگاه زیبال' })
|
||||
@Post("zibal/wallet/initiate")
|
||||
@ApiOperation({ summary: "شارژ آنلاین کیف پول از طریق درگاه زیبال" })
|
||||
@ApiOkResponse({
|
||||
description: 'لینک هدایت به درگاه پرداخت برای شارژ کیف پول',
|
||||
description: "لینک هدایت به درگاه پرداخت برای شارژ کیف پول",
|
||||
})
|
||||
async initiateWalletTopup(
|
||||
@Req() req: Request & { user: { id: string } },
|
||||
@Body() body: InitiateWalletTopupDto,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
@Headers("user-agent") userAgent?: string,
|
||||
) {
|
||||
const realIp = this.extractRealClientIp(req, ip);
|
||||
return this.paymentService.initiateWalletTopup(
|
||||
@@ -109,19 +109,19 @@ export class PaymentController {
|
||||
);
|
||||
}
|
||||
|
||||
@Get('zibal/callback')
|
||||
@Get("zibal/callback")
|
||||
@ApiOperation({
|
||||
summary: 'دریافت کالبک بازگشت از درگاه زیبال و تایید تراکنش',
|
||||
summary: "دریافت کالبک بازگشت از درگاه زیبال و تایید تراکنش",
|
||||
})
|
||||
async handleZibalCallback(
|
||||
@Req() req: Request,
|
||||
@Query() query: ZibalCallbackQueryDto,
|
||||
@Res() res: Response,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
@Headers("user-agent") userAgent?: string,
|
||||
) {
|
||||
const realIp = this.extractRealClientIp(req, ip);
|
||||
const trackId = query.trackId || '';
|
||||
const trackId = query.trackId || "";
|
||||
const success = query.success;
|
||||
const status = query.status;
|
||||
const orderId = query.orderId;
|
||||
@@ -130,7 +130,7 @@ export class PaymentController {
|
||||
|
||||
if (!trackId) {
|
||||
return res.redirect(
|
||||
`${frontendUrl}/payment/verify?success=0&message=${encodeURIComponent('شناسه پیگیری نامعتبر است')}`,
|
||||
`${frontendUrl}/payment/verify?success=0&message=${encodeURIComponent("شناسه پیگیری نامعتبر است")}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -145,37 +145,37 @@ export class PaymentController {
|
||||
|
||||
const params = new URLSearchParams({
|
||||
trackId: String(result.trackId || trackId),
|
||||
success: result.success ? '1' : '0',
|
||||
status: result.status || '',
|
||||
orderId: result.orderId || orderId || '',
|
||||
refNumber: result.refNumber || '',
|
||||
cardNumber: result.cardNumber || '',
|
||||
message: result.message || '',
|
||||
amount: String(result.amount || ''),
|
||||
type: result.type || '',
|
||||
success: result.success ? "1" : "0",
|
||||
status: result.status || "",
|
||||
orderId: result.orderId || orderId || "",
|
||||
refNumber: result.refNumber || "",
|
||||
cardNumber: result.cardNumber || "",
|
||||
message: result.message || "",
|
||||
amount: String(result.amount || ""),
|
||||
type: result.type || "",
|
||||
});
|
||||
|
||||
return res.redirect(`${frontendUrl}/payment/verify?${params.toString()}`);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'خطا در پردازش پرداخت';
|
||||
const msg = err instanceof Error ? err.message : "خطا در پردازش پرداخت";
|
||||
return res.redirect(
|
||||
`${frontendUrl}/payment/verify?success=0&trackId=${trackId}&message=${encodeURIComponent(msg)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('zibal/verify')
|
||||
@ApiOperation({ summary: 'استعلام و تایید تراکنش زیبال توسط کلاینت' })
|
||||
@Get("zibal/verify")
|
||||
@ApiOperation({ summary: "استعلام و تایید تراکنش زیبال توسط کلاینت" })
|
||||
async verifyPaymentDirect(
|
||||
@Query('trackId') trackId: string,
|
||||
@Query('success') success?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('orderId') orderId?: string,
|
||||
@Query("trackId") trackId: string,
|
||||
@Query("success") success?: string,
|
||||
@Query("status") status?: string,
|
||||
@Query("orderId") orderId?: string,
|
||||
@Ip() ip?: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
@Headers("user-agent") userAgent?: string,
|
||||
) {
|
||||
if (!trackId) {
|
||||
throw new BadRequestException('trackId is required');
|
||||
throw new BadRequestException("trackId is required");
|
||||
}
|
||||
return this.paymentService.verifyAndProcess(
|
||||
trackId,
|
||||
@@ -189,15 +189,15 @@ export class PaymentController {
|
||||
);
|
||||
}
|
||||
|
||||
@Post('zibal/callback')
|
||||
@ApiOperation({ summary: 'دریافت وبهوک / کالبک لِیزی زیبال' })
|
||||
@Post("zibal/callback")
|
||||
@ApiOperation({ summary: "دریافت وبهوک / کالبک لِیزی زیبال" })
|
||||
async handleZibalLazyCallback(
|
||||
@Body() body: ZibalCallbackQueryDto,
|
||||
@Res() res: Response,
|
||||
@Ip() ip: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
@Headers("user-agent") userAgent?: string,
|
||||
) {
|
||||
const trackId = body.trackId || '';
|
||||
const trackId = body.trackId || "";
|
||||
const success = body.success;
|
||||
const status = body.status;
|
||||
const orderId = body.orderId;
|
||||
@@ -205,7 +205,7 @@ export class PaymentController {
|
||||
if (!trackId) {
|
||||
return res
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.json({ success: false, message: 'trackId is required' });
|
||||
.json({ success: false, message: "trackId is required" });
|
||||
}
|
||||
|
||||
const result = await this.paymentService.verifyAndProcess(
|
||||
@@ -221,16 +221,16 @@ export class PaymentController {
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('verify-status/:trackId')
|
||||
@ApiOperation({ summary: 'استعلام و دریافت وضعیت تراکنش پرداخت با TrackID' })
|
||||
@Get("verify-status/:trackId")
|
||||
@ApiOperation({ summary: "استعلام و دریافت وضعیت تراکنش پرداخت با TrackID" })
|
||||
async getTransactionStatus(
|
||||
@Req() req: { user: { id: string; role?: string } },
|
||||
@Param('trackId') trackId: string,
|
||||
@Param("trackId") trackId: string,
|
||||
) {
|
||||
const isAdmin =
|
||||
req.user?.role === 'Admin' ||
|
||||
req.user?.role === 'ADMIN' ||
|
||||
req.user?.role === 'SuperAdmin';
|
||||
req.user?.role === "Admin" ||
|
||||
req.user?.role === "ADMIN" ||
|
||||
req.user?.role === "SuperAdmin";
|
||||
return this.paymentService.getTransaction(trackId, req.user?.id, isAdmin);
|
||||
}
|
||||
|
||||
@@ -239,19 +239,19 @@ export class PaymentController {
|
||||
// ==========================================
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/wallets')
|
||||
@ApiOperation({ summary: 'دریافت لیست کیفپولهای زیبال و موجودی آنها' })
|
||||
@Get("admin/wallets")
|
||||
@ApiOperation({ summary: "دریافت لیست کیفپولهای زیبال و موجودی آنها" })
|
||||
async getAdminWallets() {
|
||||
return this.zibalService.getWalletList();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/refund')
|
||||
@ApiOperation({ summary: 'درخواست استرداد وجه تراکنش (Refund یا Reverse)' })
|
||||
@Post("admin/refund")
|
||||
@ApiOperation({ summary: "درخواست استرداد وجه تراکنش (Refund یا Reverse)" })
|
||||
async createRefund(
|
||||
@Body()
|
||||
body: {
|
||||
@@ -267,10 +267,10 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/refund/inquiry')
|
||||
@ApiOperation({ summary: 'استعلام وضعیت استرداد وجه' })
|
||||
@Post("admin/refund/inquiry")
|
||||
@ApiOperation({ summary: "استعلام وضعیت استرداد وجه" })
|
||||
async inquireRefund(
|
||||
@Body()
|
||||
body: {
|
||||
@@ -282,10 +282,10 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/refund/list')
|
||||
@ApiOperation({ summary: 'گزارش لیست استردادهای انجام شده' })
|
||||
@Post("admin/refund/list")
|
||||
@ApiOperation({ summary: "گزارش لیست استردادهای انجام شده" })
|
||||
async getRefundList(
|
||||
@Body()
|
||||
body: {
|
||||
@@ -301,11 +301,11 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/gateway-report')
|
||||
@Post("admin/gateway-report")
|
||||
@ApiOperation({
|
||||
summary: 'گزارش مستقیم تراکنشهای درگاه زیبال از سرور زیبال',
|
||||
summary: "گزارش مستقیم تراکنشهای درگاه زیبال از سرور زیبال",
|
||||
})
|
||||
async getGatewayReport(
|
||||
@Body()
|
||||
@@ -326,11 +326,11 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/checkout-report')
|
||||
@Post("admin/checkout-report")
|
||||
@ApiOperation({
|
||||
summary: 'گزارش تسویهها و واریزیهای درگاه و کیفپول زیبال',
|
||||
summary: "گزارش تسویهها و واریزیهای درگاه و کیفپول زیبال",
|
||||
})
|
||||
async getCheckoutReport(
|
||||
@Body()
|
||||
@@ -346,10 +346,10 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/checkout-queue')
|
||||
@ApiOperation({ summary: 'گزارش صف تسویههای در انتظار زیبال' })
|
||||
@Get("admin/checkout-queue")
|
||||
@ApiOperation({ summary: "گزارش صف تسویههای در انتظار زیبال" })
|
||||
async getCheckoutQueueReport() {
|
||||
return this.zibalService.getCheckoutQueueReport();
|
||||
}
|
||||
@@ -359,19 +359,19 @@ export class PaymentController {
|
||||
// ==========================================
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/sub-merchants')
|
||||
@ApiOperation({ summary: 'لیست ذینفعهای ثبتشده در زیبال' })
|
||||
async getSubMerchants(@Query('page') page = '1', @Query('size') size = '20') {
|
||||
@Get("admin/sub-merchants")
|
||||
@ApiOperation({ summary: "لیست ذینفعهای ثبتشده در زیبال" })
|
||||
async getSubMerchants(@Query("page") page = "1", @Query("size") size = "20") {
|
||||
return this.zibalService.getSubMerchantList(Number(page), Number(size));
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/sub-merchants')
|
||||
@ApiOperation({ summary: 'ثبت ذینفع جدید برای تسهیم' })
|
||||
@Post("admin/sub-merchants")
|
||||
@ApiOperation({ summary: "ثبت ذینفع جدید برای تسهیم" })
|
||||
async createSubMerchant(
|
||||
@Body() body: { bankAccount: string; name: string; callbackUrl?: string },
|
||||
) {
|
||||
@@ -379,10 +379,10 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Put('admin/sub-merchants')
|
||||
@ApiOperation({ summary: 'ویرایش ذینفع غیرفعال' })
|
||||
@Put("admin/sub-merchants")
|
||||
@ApiOperation({ summary: "ویرایش ذینفع غیرفعال" })
|
||||
async editSubMerchant(
|
||||
@Body() body: { id: string; bankAccount: string; name: string },
|
||||
) {
|
||||
@@ -394,74 +394,74 @@ export class PaymentController {
|
||||
// ==========================================
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/accounts')
|
||||
@ApiOperation({ summary: 'لیست حسابهای متصل به بانکداری شرکتی زیبال' })
|
||||
async getEBankAccounts(@Query('active') active?: string) {
|
||||
const activeAccounts = active !== undefined ? active === 'true' : undefined;
|
||||
@Get("admin/ebank/accounts")
|
||||
@ApiOperation({ summary: "لیست حسابهای متصل به بانکداری شرکتی زیبال" })
|
||||
async getEBankAccounts(@Query("active") active?: string) {
|
||||
const activeAccounts = active !== undefined ? active === "true" : undefined;
|
||||
return this.zibalEBankService.getAccountList(activeAccounts);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/balance')
|
||||
@ApiOperation({ summary: 'دریافت موجودی حساب بانکداری شرکتی' })
|
||||
@Get("admin/ebank/balance")
|
||||
@ApiOperation({ summary: "دریافت موجودی حساب بانکداری شرکتی" })
|
||||
async getEBankBalance(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('update') update?: string,
|
||||
@Query("accountId") accountId?: string,
|
||||
@Query("update") update?: string,
|
||||
) {
|
||||
return this.zibalEBankService.getAccountBalance(
|
||||
accountId,
|
||||
update === 'true',
|
||||
update === "true",
|
||||
);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/statements')
|
||||
@ApiOperation({ summary: 'دریافت صورتحساب بانکی حساب متصل' })
|
||||
@Get("admin/ebank/statements")
|
||||
@ApiOperation({ summary: "دریافت صورتحساب بانکی حساب متصل" })
|
||||
async getEBankStatements(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('fromDate') fromDate?: string,
|
||||
@Query('toDate') toDate?: string,
|
||||
@Query('update') update?: string,
|
||||
@Query('size') size = '20',
|
||||
@Query('page') page = '1',
|
||||
@Query("accountId") accountId?: string,
|
||||
@Query("fromDate") fromDate?: string,
|
||||
@Query("toDate") toDate?: string,
|
||||
@Query("update") update?: string,
|
||||
@Query("size") size = "20",
|
||||
@Query("page") page = "1",
|
||||
) {
|
||||
return this.zibalEBankService.getStatementList({
|
||||
accountId,
|
||||
fromDate,
|
||||
toDate,
|
||||
update: update === 'true',
|
||||
update: update === "true",
|
||||
size: Number(size),
|
||||
page: Number(page),
|
||||
});
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/ebank/checkout')
|
||||
@ApiOperation({ summary: 'ثبت انتقال وجه پایا / ساتنا / پل از حساب بانکی' })
|
||||
@Post("admin/ebank/checkout")
|
||||
@ApiOperation({ summary: "ثبت انتقال وجه پایا / ساتنا / پل از حساب بانکی" })
|
||||
async createEBankCheckout(@Body() body: CreateEBankCheckoutDto) {
|
||||
return this.zibalEBankService.createCheckout(body);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/checkouts')
|
||||
@ApiOperation({ summary: 'لیست انتقال وجههای بانکداری شرکتی' })
|
||||
@Get("admin/ebank/checkouts")
|
||||
@ApiOperation({ summary: "لیست انتقال وجههای بانکداری شرکتی" })
|
||||
async getEBankCheckoutList(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('fromDate') fromDate?: string,
|
||||
@Query('toDate') toDate?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('size') size = '20',
|
||||
@Query('page') page = '1',
|
||||
@Query("accountId") accountId?: string,
|
||||
@Query("fromDate") fromDate?: string,
|
||||
@Query("toDate") toDate?: string,
|
||||
@Query("status") status?: string,
|
||||
@Query("size") size = "20",
|
||||
@Query("page") page = "1",
|
||||
) {
|
||||
return this.zibalEBankService.getCheckoutList({
|
||||
accountId,
|
||||
@@ -474,10 +474,10 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/ebank/checkout/cancel')
|
||||
@ApiOperation({ summary: 'لغو انتقال وجههای در صف' })
|
||||
@Post("admin/ebank/checkout/cancel")
|
||||
@ApiOperation({ summary: "لغو انتقال وجههای در صف" })
|
||||
async cancelEBankCheckout(
|
||||
@Body() body: { checkoutIds: string[]; accountId?: string },
|
||||
) {
|
||||
@@ -488,17 +488,17 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/ebank/identified-payments')
|
||||
@ApiOperation({ summary: 'لیست واریزیهای شناسه دار' })
|
||||
@Get("admin/ebank/identified-payments")
|
||||
@ApiOperation({ summary: "لیست واریزیهای شناسه دار" })
|
||||
async getEBankIdentifiedPayments(
|
||||
@Query('accountId') accountId?: string,
|
||||
@Query('fromDate') fromDate?: string,
|
||||
@Query('toDate') toDate?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('size') size = '20',
|
||||
@Query('page') page = '1',
|
||||
@Query("accountId") accountId?: string,
|
||||
@Query("fromDate") fromDate?: string,
|
||||
@Query("toDate") toDate?: string,
|
||||
@Query("status") status?: string,
|
||||
@Query("size") size = "20",
|
||||
@Query("page") page = "1",
|
||||
) {
|
||||
return this.zibalEBankService.getIdentifiedPaymentList({
|
||||
accountId,
|
||||
@@ -511,10 +511,10 @@ export class PaymentController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/ebank/identified-payments/status')
|
||||
@ApiOperation({ summary: 'تایید یا رد واریزی شناسه دار' })
|
||||
@Post("admin/ebank/identified-payments/status")
|
||||
@ApiOperation({ summary: "تایید یا رد واریزی شناسه دار" })
|
||||
async changeIdentifiedPaymentStatus(
|
||||
@Body() body: { transactionId: string; status: 2 | 3; accountId?: string },
|
||||
) {
|
||||
@@ -528,40 +528,40 @@ export class PaymentController {
|
||||
// --- ADMIN ENDPOINTS FOR TRANSACTION LOGS, DIAGNOSTICS & HEALTH CHECK ---
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/transactions')
|
||||
@ApiOperation({ summary: 'مدیریت و مشاهده تمامی لاگها و تراکنشهای پرداخت' })
|
||||
@Get("admin/transactions")
|
||||
@ApiOperation({ summary: "مدیریت و مشاهده تمامی لاگها و تراکنشهای پرداخت" })
|
||||
async getAdminTransactions(@Query() query: AdminTransactionFilterDto) {
|
||||
return this.paymentService.getAdminTransactions(query);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/stats')
|
||||
@ApiOperation({ summary: 'آمار کلی تراکنشها و حجم مبالغ پرداختی' })
|
||||
@Get("admin/stats")
|
||||
@ApiOperation({ summary: "آمار کلی تراکنشها و حجم مبالغ پرداختی" })
|
||||
async getAdminStats() {
|
||||
return this.paymentService.getAdminTransactionStats();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/reconcile')
|
||||
@Post("admin/reconcile")
|
||||
@ApiOperation({
|
||||
summary: 'اجرای فرایند انطباق و استعلام خودکار تراکنشهای بلاتکلیف',
|
||||
summary: "اجرای فرایند انطباق و استعلام خودکار تراکنشهای بلاتکلیف",
|
||||
})
|
||||
async reconcilePending() {
|
||||
return this.paymentService.reconcilePendingTransactions();
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/inquiry')
|
||||
@Post("admin/inquiry")
|
||||
@ApiOperation({
|
||||
summary: 'استعلام زنده وضعیت تراکنش با trackId یا transactionId',
|
||||
summary: "استعلام زنده وضعیت تراکنش با trackId یا transactionId",
|
||||
})
|
||||
async liveInquiryPost(
|
||||
@Body() body: { trackId?: string | number; transactionId?: string },
|
||||
@@ -579,51 +579,51 @@ export class PaymentController {
|
||||
// Direct Zibal inquiry fallback if transaction record not found
|
||||
return this.paymentService.inquiryDirectZibal(String(body.trackId));
|
||||
}
|
||||
throw new BadRequestException('trackId یا transactionId الزامی است');
|
||||
throw new BadRequestException("trackId یا transactionId الزامی است");
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/live-inquiry/:id')
|
||||
@ApiOperation({ summary: 'استعلام زنده وضعیت تراکنش از سرور زیبال' })
|
||||
async liveInquiry(@Param('id') id: string) {
|
||||
@Get("admin/live-inquiry/:id")
|
||||
@ApiOperation({ summary: "استعلام زنده وضعیت تراکنش از سرور زیبال" })
|
||||
async liveInquiry(@Param("id") id: string) {
|
||||
return this.paymentService.adminLiveInquiry(id);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/manual-verify/:id')
|
||||
@Post("admin/manual-verify/:id")
|
||||
@ApiOperation({
|
||||
summary: 'تایید دستی تراکنش یا فیش واریزی کارتبهکارت توسط ادمین',
|
||||
summary: "تایید دستی تراکنش یا فیش واریزی کارتبهکارت توسط ادمین",
|
||||
})
|
||||
async manualVerify(
|
||||
@Param('id') id: string,
|
||||
@Param("id") id: string,
|
||||
@Body() body: { adminNote?: string },
|
||||
) {
|
||||
return this.paymentService.adminManualVerify(id, body.adminNote);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/manual-reject/:id')
|
||||
@ApiOperation({ summary: 'رد دستی تراکنش پرداخت توسط ادمین' })
|
||||
@Post("admin/manual-reject/:id")
|
||||
@ApiOperation({ summary: "رد دستی تراکنش پرداخت توسط ادمین" })
|
||||
async manualReject(
|
||||
@Param('id') id: string,
|
||||
@Param("id") id: string,
|
||||
@Body() body: { reason?: string },
|
||||
) {
|
||||
return this.paymentService.adminManualReject(id, body.reason);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Roles("Admin")
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/health')
|
||||
@Get("admin/health")
|
||||
@ApiOperation({
|
||||
summary:
|
||||
'بررسی وضعیت آنلاین بودن و سلامت درگاه پرداخت (Health Check & Latency)',
|
||||
"بررسی وضعیت آنلاین بودن و سلامت درگاه پرداخت (Health Check & Latency)",
|
||||
})
|
||||
async getHealth() {
|
||||
return this.paymentService.checkGatewayHealth();
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PaymentController } from './payment.controller';
|
||||
import { PaymentService } from './payment.service';
|
||||
import { ZibalService } from './zibal.service';
|
||||
import { ZibalEBankService } from './zibal-ebank.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { SmsModule } from '../common/sms.module';
|
||||
import { Module } from "@nestjs/common";
|
||||
import { PaymentController } from "./payment.controller";
|
||||
import { PaymentService } from "./payment.service";
|
||||
import { ZibalService } from "./zibal.service";
|
||||
import { ZibalEBankService } from "./zibal-ebank.service";
|
||||
import { PrismaModule } from "../prisma/prisma.module";
|
||||
import { SmsModule } from "../common/sms.module";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, SmsModule],
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { PaymentService } from "./payment.service";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { ZibalService } from "./zibal.service";
|
||||
import { SmsService } from "../common/services/sms.service";
|
||||
import { BadRequestException, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
describe("PaymentService", () => {
|
||||
let service: PaymentService;
|
||||
|
||||
const mockPrisma = {
|
||||
order: {
|
||||
findFirst: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
paymentTransaction: {
|
||||
create: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
update: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
aggregate: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
inventoryReservation: {
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
product: {
|
||||
update: jest.fn(),
|
||||
},
|
||||
coupon: {
|
||||
update: jest.fn(),
|
||||
},
|
||||
walletTransaction: {
|
||||
create: jest.fn(),
|
||||
},
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
|
||||
const mockZibalService = {
|
||||
getBackendUrl: jest.fn().mockResolvedValue("https://canina.ir/api"),
|
||||
requestPayment: jest.fn(),
|
||||
verifyPayment: jest.fn(),
|
||||
inquiryPayment: jest.fn(),
|
||||
getResultMessage: jest.fn((code) => `Error code ${code}`),
|
||||
getStatusMessage: jest.fn((status) => `Status code ${status}`),
|
||||
getStartUrl: jest.fn(
|
||||
(trackId) => `https://gateway.zibal.ir/start/${trackId}`,
|
||||
),
|
||||
checkHealth: jest.fn().mockResolvedValue({ status: "ok" }),
|
||||
};
|
||||
|
||||
const mockSmsService = {
|
||||
triggerEvent: jest.fn().mockResolvedValue(true),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
mockPrisma.$transaction.mockImplementation(
|
||||
(callback: (tx: typeof mockPrisma) => Promise<unknown>) =>
|
||||
callback(mockPrisma),
|
||||
);
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
PaymentService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
{ provide: ZibalService, useValue: mockZibalService },
|
||||
{ provide: SmsService, useValue: mockSmsService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<PaymentService>(PaymentService);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe("initiateOrderPayment", () => {
|
||||
it("should throw NotFoundException if order does not exist", async () => {
|
||||
mockPrisma.order.findFirst.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.initiateOrderPayment("u-1", "ord-404"),
|
||||
).rejects.toThrow(NotFoundException);
|
||||
});
|
||||
|
||||
it("should throw BadRequestException if order is already shipped", async () => {
|
||||
mockPrisma.order.findFirst.mockResolvedValue({
|
||||
id: "ord-1",
|
||||
status: "shipped",
|
||||
totalAmount: 100000,
|
||||
});
|
||||
await expect(
|
||||
service.initiateOrderPayment("u-1", "ord-1"),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("should initiate payment and return zibal paymentUrl", async () => {
|
||||
mockPrisma.order.findFirst.mockResolvedValue({
|
||||
id: "ord-1",
|
||||
userId: "u-1",
|
||||
status: "pending",
|
||||
totalAmount: 250000,
|
||||
user: { mobile: "09121234567" },
|
||||
});
|
||||
mockPrisma.paymentTransaction.create.mockResolvedValue({
|
||||
id: "tx-1",
|
||||
});
|
||||
mockZibalService.requestPayment.mockResolvedValue({
|
||||
result: 100,
|
||||
trackId: 12345678,
|
||||
});
|
||||
mockPrisma.paymentTransaction.update.mockResolvedValue({
|
||||
id: "tx-1",
|
||||
trackId: "12345678",
|
||||
});
|
||||
|
||||
const res = await service.initiateOrderPayment("u-1", "ord-1");
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.trackId).toBe("12345678");
|
||||
expect(res.paymentUrl).toBe("https://gateway.zibal.ir/start/12345678");
|
||||
expect(mockPrisma.paymentTransaction.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
orderId: "ord-1",
|
||||
amountRials: BigInt(2500000),
|
||||
gateway: "zibal",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyAndProcess (Idempotency & Security)", () => {
|
||||
it("should enforce idempotency when transaction is already VERIFIED", async () => {
|
||||
mockPrisma.paymentTransaction.findUnique.mockResolvedValue({
|
||||
id: "tx-1",
|
||||
status: "VERIFIED",
|
||||
trackId: "tr-1",
|
||||
amount: new Prisma.Decimal(250000),
|
||||
orderId: "ord-1",
|
||||
});
|
||||
|
||||
const res = await service.verifyAndProcess("tr-1");
|
||||
|
||||
expect(res.alreadyVerified).toBe(true);
|
||||
expect(res.status).toBe("VERIFIED");
|
||||
expect(mockZibalService.verifyPayment).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should fail transaction and release inventory reservations if user cancelled at gateway", async () => {
|
||||
mockPrisma.paymentTransaction.findUnique.mockResolvedValue({
|
||||
id: "tx-1",
|
||||
status: "PENDING",
|
||||
trackId: "tr-1",
|
||||
orderId: "ord-1",
|
||||
});
|
||||
|
||||
const res = await service.verifyAndProcess("tr-1", "0", "3");
|
||||
|
||||
expect(res.success).toBe(false);
|
||||
expect(res.status).toBe("FAILED");
|
||||
expect(mockPrisma.inventoryReservation.updateMany).toHaveBeenCalledWith({
|
||||
where: { orderId: "ord-1", status: "ACTIVE" },
|
||||
data: { status: "RELEASED" },
|
||||
});
|
||||
});
|
||||
|
||||
it("should detect amount mismatch security anomaly and mark transaction FAILED", async () => {
|
||||
mockPrisma.paymentTransaction.findUnique.mockResolvedValue({
|
||||
id: "tx-1",
|
||||
status: "PENDING",
|
||||
trackId: "tr-1",
|
||||
amountRials: BigInt(5000000),
|
||||
orderId: "ord-1",
|
||||
});
|
||||
mockZibalService.verifyPayment.mockResolvedValue({
|
||||
result: 100,
|
||||
amount: 1000000, // attacker tried to pay less!
|
||||
});
|
||||
|
||||
const res = await service.verifyAndProcess("tr-1", "1", "1");
|
||||
|
||||
expect(res.success).toBe(false);
|
||||
expect(res.message).toContain("مغایرت در مبلغ");
|
||||
expect(mockPrisma.paymentTransaction.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
status: "FAILED",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should consume inventory reservation and update order on verified payment", async () => {
|
||||
mockPrisma.paymentTransaction.findUnique.mockResolvedValue({
|
||||
id: "tx-1",
|
||||
userId: "u-1",
|
||||
status: "PENDING",
|
||||
trackId: "tr-valid",
|
||||
type: "ORDER",
|
||||
amountRials: BigInt(5000000),
|
||||
orderId: "ord-1",
|
||||
order: {
|
||||
id: "ord-1",
|
||||
trackingNumber: "CAN-100",
|
||||
shippingAddress: "تهران، ولیعصر",
|
||||
orderItems: [{ productId: "p-1", quantity: 2 }],
|
||||
},
|
||||
});
|
||||
mockZibalService.verifyPayment.mockResolvedValue({
|
||||
result: 100,
|
||||
amount: 5000000,
|
||||
refNumber: 998877,
|
||||
cardNumber: "603799******1234",
|
||||
});
|
||||
mockPrisma.paymentTransaction.updateMany.mockResolvedValue({ count: 1 });
|
||||
mockPrisma.order.findUnique.mockResolvedValue({
|
||||
id: "ord-1",
|
||||
shippingAddress: "تهران، خیابان آزادی",
|
||||
orderItems: [
|
||||
{
|
||||
productId: "p-1",
|
||||
quantity: 2,
|
||||
product: { nameFa: "کانیهیدروکس" },
|
||||
},
|
||||
],
|
||||
});
|
||||
mockPrisma.product.update.mockResolvedValue({ id: "p-1", stock: 8 });
|
||||
|
||||
const res = await service.verifyAndProcess("tr-valid", "1", "1");
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.status).toBe("VERIFIED");
|
||||
expect(mockPrisma.order.update).toHaveBeenCalledWith({
|
||||
where: { id: "ord-1" },
|
||||
data: expect.objectContaining({
|
||||
status: "processing",
|
||||
paymentMethod: "online",
|
||||
}),
|
||||
});
|
||||
expect(mockPrisma.inventoryReservation.updateMany).toHaveBeenCalledWith({
|
||||
where: { orderId: "ord-1", status: "ACTIVE" },
|
||||
data: { status: "CONSUMED" },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { ZibalEBankService } from "./zibal-ebank.service";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
describe("ZibalEBankService", () => {
|
||||
let service: ZibalEBankService;
|
||||
|
||||
const mockPrisma = {
|
||||
uiText: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
const originalToken = process.env.ZIBAL_EBANK_TOKEN;
|
||||
const originalAccount = process.env.ZIBAL_EBANK_ACCOUNT_ID;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockPrisma.uiText.findUnique.mockReset();
|
||||
global.fetch = jest
|
||||
.fn()
|
||||
.mockRejectedValue(new Error("Unexpected external request"));
|
||||
delete process.env.ZIBAL_EBANK_TOKEN;
|
||||
delete process.env.ZIBAL_EBANK_ACCOUNT_ID;
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
ZibalEBankService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ZibalEBankService>(ZibalEBankService);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.useRealTimers();
|
||||
global.fetch = originalFetch;
|
||||
if (originalToken === undefined) delete process.env.ZIBAL_EBANK_TOKEN;
|
||||
else process.env.ZIBAL_EBANK_TOKEN = originalToken;
|
||||
if (originalAccount === undefined)
|
||||
delete process.env.ZIBAL_EBANK_ACCOUNT_ID;
|
||||
else process.env.ZIBAL_EBANK_ACCOUNT_ID = originalAccount;
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe("Tokens & Account ID Resolvers", () => {
|
||||
it("should read access token from db if available", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({
|
||||
key: "ZIBAL_EBANK_TOKEN",
|
||||
value: "custom-token-xyz",
|
||||
});
|
||||
const token = await service.getAccessToken();
|
||||
expect(token).toBe("custom-token-xyz");
|
||||
});
|
||||
|
||||
it("should fallback to env variable if token not found in db", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue(null);
|
||||
const originalEnv = process.env.ZIBAL_EBANK_TOKEN;
|
||||
process.env.ZIBAL_EBANK_TOKEN = "env-ebank-token";
|
||||
|
||||
const token = await service.getAccessToken();
|
||||
expect(token).toBe("env-ebank-token");
|
||||
|
||||
if (originalEnv) process.env.ZIBAL_EBANK_TOKEN = originalEnv;
|
||||
else delete process.env.ZIBAL_EBANK_TOKEN;
|
||||
});
|
||||
|
||||
it("should read default account ID from db if available", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({
|
||||
key: "ZIBAL_EBANK_ACCOUNT_ID",
|
||||
value: "acc-999",
|
||||
});
|
||||
const accountId = await service.getDefaultAccountId();
|
||||
expect(accountId).toBe("acc-999");
|
||||
});
|
||||
|
||||
it("should fallback to env variable for account ID", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue(null);
|
||||
const originalEnv = process.env.ZIBAL_EBANK_ACCOUNT_ID;
|
||||
process.env.ZIBAL_EBANK_ACCOUNT_ID = "acc-env-123";
|
||||
|
||||
const accountId = await service.getDefaultAccountId();
|
||||
expect(accountId).toBe("acc-env-123");
|
||||
|
||||
if (originalEnv) process.env.ZIBAL_EBANK_ACCOUNT_ID = originalEnv;
|
||||
else delete process.env.ZIBAL_EBANK_ACCOUNT_ID;
|
||||
});
|
||||
});
|
||||
|
||||
describe("Checkouts (create, inquire, list, cancel)", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.uiText.findUnique.mockImplementation(({ where }) => {
|
||||
if (where.key === "ZIBAL_EBANK_TOKEN") return { value: "test-token" };
|
||||
if (where.key === "ZIBAL_EBANK_ACCOUNT_ID")
|
||||
return { value: "acc-main" };
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error when creating checkout without accountId and no default configured", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue(null);
|
||||
delete process.env.ZIBAL_EBANK_ACCOUNT_ID;
|
||||
process.env.ZIBAL_EBANK_TOKEN = "test-token";
|
||||
|
||||
await expect(
|
||||
service.createCheckout({
|
||||
amount: 5000000,
|
||||
iban: "IR123456789012345678901234",
|
||||
}),
|
||||
).rejects.toThrow("شناسه حساب زیبال (accountId) الزامی است.");
|
||||
});
|
||||
|
||||
it("should create checkout successfully with formatted payload", async () => {
|
||||
const mockApiResponse = {
|
||||
result: 1,
|
||||
message: "success",
|
||||
checkoutId: "chk-1",
|
||||
};
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.createCheckout({
|
||||
amount: 2500000,
|
||||
iban: "ir 01 2345 6789 0123 4567 8901 23",
|
||||
description: "تسویه حساب تأمینکننده",
|
||||
uniqueCode: "PAY-CUSTOM-1",
|
||||
});
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://api.zibal.ir/ebank/v1/account/checkout/create/",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
Authorization: "Bearer test-token",
|
||||
"Content-Type": "application/json",
|
||||
}),
|
||||
body: JSON.stringify({
|
||||
accountId: "acc-main",
|
||||
amount: 2500000,
|
||||
iban: "IR012345678901234567890123",
|
||||
reasonCode: 18,
|
||||
delay: -1,
|
||||
uniqueCode: "PAY-CUSTOM-1",
|
||||
description: "تسویه حساب تأمینکننده",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should inquire checkout status via uniqueCode or trackerId", async () => {
|
||||
const mockApiResponse = { result: 1, status: 2, amount: 2500000 };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.inquireCheckout({
|
||||
uniqueCode: "PAY-CUSTOM-1",
|
||||
});
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://api.zibal.ir/ebank/v1/account/checkout/inquire/?accountId=acc-main&uniqueCode=PAY-CUSTOM-1",
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should fetch checkout list with filters and default dates", async () => {
|
||||
const mockApiResponse = { result: 1, checkouts: [] };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.getCheckoutList({
|
||||
status: 1,
|
||||
page: 2,
|
||||
size: 15,
|
||||
});
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
expect.stringMatching(
|
||||
/https:\/\/api\.zibal\.ir\/ebank\/v1\/account\/checkout\/list\/\?accountId=acc-main.*&status=1&size=15&page=2/,
|
||||
),
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should cancel checkout list successfully", async () => {
|
||||
const mockApiResponse = { result: 1, message: "cancelled" };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.cancelCheckout(["chk-1", "chk-2"]);
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://api.zibal.ir/ebank/v1/account/checkout/cancel/",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
accountId: "acc-main",
|
||||
checkoutIds: ["chk-1", "chk-2"],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Accounts & Statements", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.uiText.findUnique.mockImplementation(({ where }) => {
|
||||
if (where.key === "ZIBAL_EBANK_TOKEN") return { value: "test-token" };
|
||||
if (where.key === "ZIBAL_EBANK_ACCOUNT_ID")
|
||||
return { value: "acc-main" };
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
it("should get accounts list", async () => {
|
||||
const mockApiResponse = { result: 1, accounts: [{ id: "acc-1" }] };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.getAccountList(true);
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://api.zibal.ir/ebank/v1/account/list/?activeAccounts=true",
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should get account balance", async () => {
|
||||
const mockApiResponse = { result: 1, balance: 100000000 };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.getAccountBalance("acc-custom", false);
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://api.zibal.ir/ebank/v1/account/balance/?accountId=acc-custom&update=false",
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should get statement list with default date ranges", async () => {
|
||||
const mockApiResponse = { result: 1, statements: [] };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.getStatementList({ page: 1, size: 20 });
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
expect.stringMatching(
|
||||
/https:\/\/api\.zibal\.ir\/ebank\/v1\/account\/statement\/list\/\?accountId=acc-main.*&update=false&size=20&page=1/,
|
||||
),
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Identified Payments", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.uiText.findUnique.mockImplementation(({ where }) => {
|
||||
if (where.key === "ZIBAL_EBANK_TOKEN") return { value: "test-token" };
|
||||
if (where.key === "ZIBAL_EBANK_ACCOUNT_ID")
|
||||
return { value: "acc-main" };
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
it("should fetch identified payments list", async () => {
|
||||
const mockApiResponse = { result: 1, data: [] };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.getIdentifiedPaymentList({ status: 0 });
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
expect.stringMatching(
|
||||
/https:\/\/api\.zibal\.ir\/ebank\/v1\/account\/identified-payment\/list\/\?accountId=acc-main.*&status=0&size=20&page=1/,
|
||||
),
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should change identified payment status (verify/reject)", async () => {
|
||||
const mockApiResponse = { result: 1, message: "Status updated" };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.changeIdentifiedPaymentStatus("tx-100", 2);
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://api.zibal.ir/ebank/v1/account/identified-payment/change-status/",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
accountId: "acc-main",
|
||||
transactionId: "tx-100",
|
||||
status: 2,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should inquire identified payment status", async () => {
|
||||
const mockApiResponse = { result: 1, status: 2 };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockApiResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.inquireIdentifiedPayment("tx-100");
|
||||
|
||||
expect(res).toEqual(mockApiResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://api.zibal.ir/ebank/v1/account/identified-payment/inquire/?accountId=acc-main&transactionId=tx-100",
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("transport safety boundaries", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({ value: " test-token " });
|
||||
});
|
||||
|
||||
it("blocks requests when the configured token is whitespace", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({ value: " " });
|
||||
await expect(service.getAccountList()).rejects.toThrow(
|
||||
"ZIBAL_EBANK_TOKEN",
|
||||
);
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to environment settings when the database is unavailable", async () => {
|
||||
mockPrisma.uiText.findUnique.mockRejectedValue(new Error("DB offline"));
|
||||
process.env.ZIBAL_EBANK_TOKEN = "fallback-token";
|
||||
process.env.ZIBAL_EBANK_ACCOUNT_ID = "fallback-account";
|
||||
await expect(service.getAccessToken()).resolves.toBe("fallback-token");
|
||||
await expect(service.getDefaultAccountId()).resolves.toBe(
|
||||
"fallback-account",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["network", "json"])(
|
||||
"propagates %s failure and clears the abort timer without retrying",
|
||||
async (kind) => {
|
||||
jest.useFakeTimers();
|
||||
const error = new Error("transport failed");
|
||||
const fetchMock = global.fetch as jest.Mock;
|
||||
if (kind === "network") fetchMock.mockRejectedValue(error);
|
||||
else
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
json: jest.fn().mockRejectedValue(error),
|
||||
});
|
||||
await expect(service.getAccountList()).rejects.toBe(error);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("aborts a stalled request after 15 seconds without retrying", async () => {
|
||||
jest.useFakeTimers();
|
||||
const error = new Error("aborted");
|
||||
(global.fetch as jest.Mock).mockImplementation(
|
||||
(_url, options: RequestInit) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
options.signal?.addEventListener("abort", () => reject(error));
|
||||
}),
|
||||
);
|
||||
const assertion = expect(service.getAccountList()).rejects.toBe(error);
|
||||
await jest.advanceTimersByTimeAsync(14999);
|
||||
const options = (global.fetch as jest.Mock).mock
|
||||
.calls[0][1] as RequestInit;
|
||||
expect(options.signal?.aborted).toBe(false);
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
await assertion;
|
||||
expect(options.signal?.aborted).toBe(true);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("encodes query values instead of allowing parameter injection", async () => {
|
||||
(global.fetch as jest.Mock).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ result: 1 }),
|
||||
});
|
||||
await service.inquireCheckout({
|
||||
accountId: "account&other=1",
|
||||
uniqueCode: "PAY ?&=",
|
||||
});
|
||||
const url = new URL((global.fetch as jest.Mock).mock.calls[0][0]);
|
||||
expect(url.origin).toBe("https://api.zibal.ir");
|
||||
expect(url.searchParams.get("accountId")).toBe("account&other=1");
|
||||
expect(url.searchParams.get("uniqueCode")).toBe("PAY ?&=");
|
||||
expect(url.searchParams.has("other")).toBe(false);
|
||||
expect(url.searchParams.has("trackerId")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("security regressions", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({ value: "test-token" });
|
||||
});
|
||||
it("rejects non-success HTTP responses without trusting their JSON", async () => {
|
||||
const json = jest.fn().mockResolvedValue({ result: 1 });
|
||||
(global.fetch as jest.Mock).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 503,
|
||||
json,
|
||||
});
|
||||
await expect(service.getAccountList()).rejects.toThrow("HTTP 503");
|
||||
expect(json).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])(
|
||||
"rejects unsafe payout amount %p before HTTP",
|
||||
async (amount) => {
|
||||
await expect(
|
||||
service.createCheckout({
|
||||
accountId: "a",
|
||||
amount,
|
||||
iban: "IR123456789012345678901234",
|
||||
}),
|
||||
).rejects.toThrow("amount");
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
it.each([
|
||||
"",
|
||||
"IR1",
|
||||
"XX123456789012345678901234",
|
||||
"IR12345678901234567890123X",
|
||||
])("rejects malformed payout destination %p before HTTP", async (iban) => {
|
||||
await expect(
|
||||
service.createCheckout({ accountId: "a", amount: 1000, iban }),
|
||||
).rejects.toThrow("iban");
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("request error handling", () => {
|
||||
it("should throw error when access token is not configured", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue(null);
|
||||
delete process.env.ZIBAL_EBANK_TOKEN;
|
||||
|
||||
await expect(service.getAccountList()).rejects.toThrow(
|
||||
"توکن دسترسی بانکداری شرکتی زیبال (ZIBAL_EBANK_TOKEN) تنظیم نشده است.",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
export interface EBankCheckoutOptions {
|
||||
amount: number; // Rial
|
||||
@@ -43,7 +43,7 @@ export interface EBankIdentifiedPaymentFilter {
|
||||
@Injectable()
|
||||
export class ZibalEBankService {
|
||||
private readonly logger = new Logger(ZibalEBankService.name);
|
||||
private readonly baseUrl = 'https://api.zibal.ir';
|
||||
private readonly baseUrl = "https://api.zibal.ir";
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@@ -53,16 +53,16 @@ export class ZibalEBankService {
|
||||
async getAccessToken(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_EBANK_TOKEN' },
|
||||
where: { key: "ZIBAL_EBANK_TOKEN" },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
if (setting && setting.value && setting.value.trim() !== "") {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_EBANK_TOKEN from db: ${e}`);
|
||||
}
|
||||
|
||||
return process.env.ZIBAL_EBANK_TOKEN || '';
|
||||
return process.env.ZIBAL_EBANK_TOKEN || "";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,22 +71,22 @@ export class ZibalEBankService {
|
||||
async getDefaultAccountId(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_EBANK_ACCOUNT_ID' },
|
||||
where: { key: "ZIBAL_EBANK_ACCOUNT_ID" },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
if (setting && setting.value && setting.value.trim() !== "") {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_EBANK_ACCOUNT_ID from db: ${e}`);
|
||||
}
|
||||
|
||||
return process.env.ZIBAL_EBANK_ACCOUNT_ID || '';
|
||||
return process.env.ZIBAL_EBANK_ACCOUNT_ID || "";
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
method?: "GET" | "POST" | "PUT" | "DELETE";
|
||||
body?: Record<string, any>;
|
||||
params?: Record<string, any>;
|
||||
} = {},
|
||||
@@ -94,7 +94,7 @@ export class ZibalEBankService {
|
||||
const token = await this.getAccessToken();
|
||||
if (!token) {
|
||||
throw new Error(
|
||||
'توکن دسترسی بانکداری شرکتی زیبال (ZIBAL_EBANK_TOKEN) تنظیم نشده است.',
|
||||
"توکن دسترسی بانکداری شرکتی زیبال (ZIBAL_EBANK_TOKEN) تنظیم نشده است.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -102,33 +102,36 @@ export class ZibalEBankService {
|
||||
if (options.params) {
|
||||
const queryParams = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(options.params)) {
|
||||
if (v !== undefined && v !== null && v !== '') {
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
queryParams.append(k, String(v));
|
||||
}
|
||||
}
|
||||
const qs = queryParams.toString();
|
||||
if (qs) {
|
||||
url += (url.includes('?') ? '&' : '?') + qs;
|
||||
url += (url.includes("?") ? "&" : "?") + qs;
|
||||
}
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 15000);
|
||||
|
||||
try {
|
||||
this.logger.log(`[Zibal EBank API] ${options.method || 'GET'} ${url}`);
|
||||
this.logger.log(`[Zibal EBank API] ${options.method || "GET"} ${url}`);
|
||||
const response = await fetch(url, {
|
||||
method: options.method || 'GET',
|
||||
method: options.method || "GET",
|
||||
headers,
|
||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Zibal EBank HTTP ${response.status}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
return data as T;
|
||||
} catch (err: unknown) {
|
||||
@@ -152,23 +155,33 @@ export class ZibalEBankService {
|
||||
async createCheckout(options: EBankCheckoutOptions) {
|
||||
const accountId = options.accountId || (await this.getDefaultAccountId());
|
||||
if (!accountId) {
|
||||
throw new Error('شناسه حساب زیبال (accountId) الزامی است.');
|
||||
throw new Error("شناسه حساب زیبال (accountId) الزامی است.");
|
||||
}
|
||||
|
||||
// Rial amounts must survive JSON serialization without rounding or null conversion.
|
||||
if (!Number.isSafeInteger(options.amount) || options.amount <= 0) {
|
||||
throw new Error("amount must be a positive safe integer in Rial");
|
||||
}
|
||||
const iban = options.iban.replace(/\s+/g, "").toUpperCase();
|
||||
if (!/^IR[0-9]{24}$/.test(iban)) {
|
||||
throw new Error(
|
||||
"iban must be an Iranian IBAN (IR followed by 24 digits)",
|
||||
);
|
||||
}
|
||||
const payload = {
|
||||
accountId,
|
||||
amount: options.amount,
|
||||
iban: options.iban.replace(/\s+/g, '').toUpperCase(),
|
||||
iban,
|
||||
reasonCode: options.reasonCode || 18, // 18: خرید کالا
|
||||
delay: options.delay ?? -1, // -1: instant
|
||||
uniqueCode: options.uniqueCode || `PAY-${Date.now()}`,
|
||||
description: options.description || 'انتقال وجه کنینا',
|
||||
description: options.description || "انتقال وجه کنینا",
|
||||
paymentNumber: options.paymentNumber,
|
||||
callbackUrl: options.callbackUrl,
|
||||
};
|
||||
|
||||
return this.request<any>('/ebank/v1/account/checkout/create/', {
|
||||
method: 'POST',
|
||||
return this.request<any>("/ebank/v1/account/checkout/create/", {
|
||||
method: "POST",
|
||||
body: payload,
|
||||
});
|
||||
}
|
||||
@@ -182,8 +195,8 @@ export class ZibalEBankService {
|
||||
trackerId?: string;
|
||||
}) {
|
||||
const accountId = params.accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/checkout/inquire/', {
|
||||
method: 'GET',
|
||||
return this.request<any>("/ebank/v1/account/checkout/inquire/", {
|
||||
method: "GET",
|
||||
params: {
|
||||
accountId,
|
||||
uniqueCode: params.uniqueCode,
|
||||
@@ -203,8 +216,8 @@ export class ZibalEBankService {
|
||||
).toISOString();
|
||||
const defaultTo = now.toISOString();
|
||||
|
||||
return this.request<any>('/ebank/v1/account/checkout/list/', {
|
||||
method: 'GET',
|
||||
return this.request<any>("/ebank/v1/account/checkout/list/", {
|
||||
method: "GET",
|
||||
params: {
|
||||
accountId,
|
||||
fromDate: filter.fromDate || defaultFrom,
|
||||
@@ -221,8 +234,8 @@ export class ZibalEBankService {
|
||||
*/
|
||||
async cancelCheckout(checkoutIds: string[], accountId?: string) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/checkout/cancel/', {
|
||||
method: 'POST',
|
||||
return this.request<any>("/ebank/v1/account/checkout/cancel/", {
|
||||
method: "POST",
|
||||
body: {
|
||||
accountId: targetAccountId,
|
||||
checkoutIds,
|
||||
@@ -238,8 +251,8 @@ export class ZibalEBankService {
|
||||
* دریافت لیست حسابهای متصل به بانکداری شرکتی
|
||||
*/
|
||||
async getAccountList(activeAccounts?: boolean) {
|
||||
return this.request<any>('/ebank/v1/account/list/', {
|
||||
method: 'GET',
|
||||
return this.request<any>("/ebank/v1/account/list/", {
|
||||
method: "GET",
|
||||
params: {
|
||||
activeAccounts,
|
||||
},
|
||||
@@ -251,8 +264,8 @@ export class ZibalEBankService {
|
||||
*/
|
||||
async getAccountBalance(accountId?: string, update = true) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/balance/', {
|
||||
method: 'GET',
|
||||
return this.request<any>("/ebank/v1/account/balance/", {
|
||||
method: "GET",
|
||||
params: {
|
||||
accountId: targetAccountId,
|
||||
update,
|
||||
@@ -271,8 +284,8 @@ export class ZibalEBankService {
|
||||
).toISOString();
|
||||
const defaultTo = now.toISOString();
|
||||
|
||||
return this.request<any>('/ebank/v1/account/statement/list/', {
|
||||
method: 'GET',
|
||||
return this.request<any>("/ebank/v1/account/statement/list/", {
|
||||
method: "GET",
|
||||
params: {
|
||||
accountId,
|
||||
fromDate: filter.fromDate || defaultFrom,
|
||||
@@ -299,8 +312,8 @@ export class ZibalEBankService {
|
||||
).toISOString();
|
||||
const defaultTo = now.toISOString();
|
||||
|
||||
return this.request<any>('/ebank/v1/account/identified-payment/list/', {
|
||||
method: 'GET',
|
||||
return this.request<any>("/ebank/v1/account/identified-payment/list/", {
|
||||
method: "GET",
|
||||
params: {
|
||||
accountId,
|
||||
fromDate: filter.fromDate || defaultFrom,
|
||||
@@ -322,9 +335,9 @@ export class ZibalEBankService {
|
||||
) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>(
|
||||
'/ebank/v1/account/identified-payment/change-status/',
|
||||
"/ebank/v1/account/identified-payment/change-status/",
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
body: {
|
||||
accountId: targetAccountId,
|
||||
transactionId,
|
||||
@@ -339,8 +352,8 @@ export class ZibalEBankService {
|
||||
*/
|
||||
async inquireIdentifiedPayment(transactionId: string, accountId?: string) {
|
||||
const targetAccountId = accountId || (await this.getDefaultAccountId());
|
||||
return this.request<any>('/ebank/v1/account/identified-payment/inquire/', {
|
||||
method: 'GET',
|
||||
return this.request<any>("/ebank/v1/account/identified-payment/inquire/", {
|
||||
method: "GET",
|
||||
params: {
|
||||
accountId: targetAccountId,
|
||||
transactionId,
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { ZibalService } from "./zibal.service";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
describe("ZibalService", () => {
|
||||
let service: ZibalService;
|
||||
let prisma: PrismaService;
|
||||
|
||||
const mockPrisma = {
|
||||
uiText: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
ZibalService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<ZibalService>(ZibalService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
expect(service.getGatewayName()).toBe("zibal");
|
||||
});
|
||||
|
||||
describe("Merchant & URL Resolvers", () => {
|
||||
it("should read merchant from db if available", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({
|
||||
key: "ZIBAL_MERCHANT",
|
||||
value: "custom-merchant",
|
||||
});
|
||||
const merchant = await service.getMerchant();
|
||||
expect(merchant).toBe("custom-merchant");
|
||||
});
|
||||
|
||||
it("should fallback to default sandbox if db returns null and no env set", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue(null);
|
||||
const originalEnv = process.env.ZIBAL_MERCHANT;
|
||||
delete process.env.ZIBAL_MERCHANT;
|
||||
|
||||
const merchant = await service.getMerchant();
|
||||
expect(merchant).toBe("zibal");
|
||||
|
||||
if (originalEnv) process.env.ZIBAL_MERCHANT = originalEnv;
|
||||
});
|
||||
|
||||
it("should get start URL with trackId", () => {
|
||||
const url = service.getStartUrl(987654);
|
||||
expect(url).toBe("https://gateway.zibal.ir/start/987654");
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestPayment", () => {
|
||||
it("should send payment request successfully", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({
|
||||
key: "ZIBAL_MERCHANT",
|
||||
value: "merchant-123",
|
||||
});
|
||||
|
||||
const mockResponse = {
|
||||
trackId: 102030,
|
||||
result: 100,
|
||||
message: "success",
|
||||
};
|
||||
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockResponse),
|
||||
} as any);
|
||||
|
||||
const result = await service.requestPayment({
|
||||
amountRials: 1000000,
|
||||
callbackUrl: "https://canina.ir/verify",
|
||||
orderId: "ord-123",
|
||||
description: "تست پرداخت",
|
||||
mobile: "09120000000",
|
||||
});
|
||||
|
||||
expect(result).toEqual(mockResponse);
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
"https://gateway.zibal.ir/v1/request",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when api returns non-ok status", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({
|
||||
key: "ZIBAL_MERCHANT",
|
||||
value: "merchant-123",
|
||||
});
|
||||
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: () => Promise.resolve("Invalid merchant"),
|
||||
} as any);
|
||||
|
||||
// retry delays overridden to fast
|
||||
jest
|
||||
.spyOn<any, any>(service, "callWithRetry")
|
||||
.mockImplementation((op: () => Promise<unknown>) => {
|
||||
return op();
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.requestPayment({
|
||||
amountRials: 1000000,
|
||||
callbackUrl: "https://canina.ir/verify",
|
||||
orderId: "ord-123",
|
||||
}),
|
||||
).rejects.toThrow("Zibal request HTTP 400: Invalid merchant");
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyPayment", () => {
|
||||
it("should verify payment successfully", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({
|
||||
key: "ZIBAL_MERCHANT",
|
||||
value: "merchant-123",
|
||||
});
|
||||
|
||||
const mockResponse = {
|
||||
result: 100,
|
||||
amount: 1000000,
|
||||
refNumber: "REF123456",
|
||||
status: 1,
|
||||
message: "success",
|
||||
};
|
||||
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.verifyPayment("102030");
|
||||
expect(res).toEqual(mockResponse);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inquiryPayment", () => {
|
||||
it("should inquiry payment successfully", async () => {
|
||||
mockPrisma.uiText.findUnique.mockResolvedValue({
|
||||
key: "ZIBAL_MERCHANT",
|
||||
value: "merchant-123",
|
||||
});
|
||||
|
||||
const mockResponse = {
|
||||
result: 100,
|
||||
amount: 1000000,
|
||||
status: 1,
|
||||
message: "inquiry success",
|
||||
};
|
||||
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockResponse),
|
||||
} as any);
|
||||
|
||||
const res = await service.inquiryPayment("102030");
|
||||
expect(res).toEqual(mockResponse);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import {
|
||||
IPaymentGateway,
|
||||
PaymentRequestOptions,
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
PaymentVerifyResult,
|
||||
PaymentInquiryResult,
|
||||
GatewayHealthResult,
|
||||
} from './interfaces/payment-gateway.interface';
|
||||
} from "./interfaces/payment-gateway.interface";
|
||||
|
||||
export interface ZibalRequestResponse {
|
||||
trackId: number;
|
||||
@@ -42,12 +42,12 @@ export interface ZibalInquiryResponse {
|
||||
@Injectable()
|
||||
export class ZibalService implements IPaymentGateway {
|
||||
private readonly logger = new Logger(ZibalService.name);
|
||||
private readonly baseUrl = 'https://gateway.zibal.ir';
|
||||
private readonly baseUrl = "https://gateway.zibal.ir";
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
getGatewayName(): string {
|
||||
return 'zibal';
|
||||
return "zibal";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,16 +93,16 @@ export class ZibalService implements IPaymentGateway {
|
||||
async getMerchant(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_MERCHANT' },
|
||||
where: { key: "ZIBAL_MERCHANT" },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
if (setting && setting.value && setting.value.trim() !== "") {
|
||||
return setting.value.trim();
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read ZIBAL_MERCHANT from db: ${e}`);
|
||||
}
|
||||
|
||||
return process.env.ZIBAL_MERCHANT || 'zibal';
|
||||
return process.env.ZIBAL_MERCHANT || "zibal";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,17 +111,17 @@ export class ZibalService implements IPaymentGateway {
|
||||
async getFrontendUrl(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'FRONTEND_URL' },
|
||||
where: { key: "FRONTEND_URL" },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim().replace(/\/+$/, '');
|
||||
if (setting && setting.value && setting.value.trim() !== "") {
|
||||
return setting.value.trim().replace(/\/+$/, "");
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read FRONTEND_URL from db: ${e}`);
|
||||
}
|
||||
|
||||
const envUrl = process.env.FRONTEND_URL || process.env.APP_URL;
|
||||
return envUrl ? envUrl.replace(/\/+$/, '') : 'https://canina.ir';
|
||||
return envUrl ? envUrl.replace(/\/+$/, "") : "https://canina.ir";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,23 +130,23 @@ export class ZibalService implements IPaymentGateway {
|
||||
async getBackendUrl(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'BACKEND_URL' },
|
||||
where: { key: "BACKEND_URL" },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim().replace(/\/+$/, '');
|
||||
if (setting && setting.value && setting.value.trim() !== "") {
|
||||
return setting.value.trim().replace(/\/+$/, "");
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read BACKEND_URL from db: ${e}`);
|
||||
}
|
||||
|
||||
const envUrl = process.env.BACKEND_URL || process.env.API_URL;
|
||||
if (envUrl) return envUrl.replace(/\/+$/, '');
|
||||
if (envUrl) return envUrl.replace(/\/+$/, "");
|
||||
|
||||
const frontendUrl = await this.getFrontendUrl();
|
||||
if (frontendUrl.includes('stage')) {
|
||||
return 'https://stageapi.canina.ir/api';
|
||||
if (frontendUrl.includes("stage")) {
|
||||
return "https://stageapi.canina.ir/api";
|
||||
}
|
||||
return 'https://api.canina.ir/api';
|
||||
return "https://api.canina.ir/api";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -165,7 +165,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
merchant,
|
||||
amount: params.amountRials,
|
||||
callbackUrl: params.callbackUrl,
|
||||
description: params.description || 'پرداخت سفارش در پت شاپ کنینا',
|
||||
description: params.description || "پرداخت سفارش در پت شاپ کنینا",
|
||||
orderId: params.orderId,
|
||||
mobile: params.mobile,
|
||||
nationalCode: params.nationalCode,
|
||||
@@ -182,9 +182,9 @@ export class ZibalService implements IPaymentGateway {
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/v1/request`, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
@@ -233,9 +233,9 @@ export class ZibalService implements IPaymentGateway {
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/v1/verify`, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
@@ -275,9 +275,9 @@ export class ZibalService implements IPaymentGateway {
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/v1/inquiry`, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
@@ -310,9 +310,9 @@ export class ZibalService implements IPaymentGateway {
|
||||
const timeoutId = setTimeout(() => controller.abort(), 5000);
|
||||
|
||||
const res = await fetch(`${this.baseUrl}/v1/inquiry`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ merchant, trackId: '1' }),
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ merchant, trackId: "1" }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
@@ -321,24 +321,24 @@ export class ZibalService implements IPaymentGateway {
|
||||
|
||||
if (res.ok || res.status === 400 || res.status === 200) {
|
||||
return {
|
||||
gatewayName: 'Zibal IPG',
|
||||
status: latencyMs < 1500 ? 'ONLINE' : 'DEGRADED',
|
||||
gatewayName: "Zibal IPG",
|
||||
status: latencyMs < 1500 ? "ONLINE" : "DEGRADED",
|
||||
latencyMs,
|
||||
merchantConfigured: merchant !== 'zibal',
|
||||
merchantConfigured: merchant !== "zibal",
|
||||
activeMerchant:
|
||||
merchant === 'zibal'
|
||||
? 'zibal (تستی/سندباکس)'
|
||||
merchant === "zibal"
|
||||
? "zibal (تستی/سندباکس)"
|
||||
: `${merchant.slice(0, 4)}****`,
|
||||
message: 'اتصال به درگاه زیبال با موفقیت برقرار است',
|
||||
message: "اتصال به درگاه زیبال با موفقیت برقرار است",
|
||||
checkedAt: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
gatewayName: 'Zibal IPG',
|
||||
status: 'DEGRADED',
|
||||
gatewayName: "Zibal IPG",
|
||||
status: "DEGRADED",
|
||||
latencyMs,
|
||||
merchantConfigured: merchant !== 'zibal',
|
||||
merchantConfigured: merchant !== "zibal",
|
||||
activeMerchant: merchant,
|
||||
message: `پاسخ غیرعادی سرور زیبال (${res.status})`,
|
||||
checkedAt: new Date(),
|
||||
@@ -347,10 +347,10 @@ export class ZibalService implements IPaymentGateway {
|
||||
const latencyMs = Date.now() - startTime;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
gatewayName: 'Zibal IPG',
|
||||
status: 'OFFLINE',
|
||||
gatewayName: "Zibal IPG",
|
||||
status: "OFFLINE",
|
||||
latencyMs,
|
||||
merchantConfigured: merchant !== 'zibal',
|
||||
merchantConfigured: merchant !== "zibal",
|
||||
activeMerchant: merchant,
|
||||
message: `عدم دسترسی به درگاه: ${msg}`,
|
||||
checkedAt: new Date(),
|
||||
@@ -377,7 +377,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
merchant,
|
||||
amount: params.amountRials,
|
||||
callbackUrl: params.callbackUrl,
|
||||
description: params.description || 'پرداخت سفارش (Lazy) در کنینا',
|
||||
description: params.description || "پرداخت سفارش (Lazy) در کنینا",
|
||||
orderId: params.orderId,
|
||||
mobile: params.mobile,
|
||||
nationalCode: params.nationalCode,
|
||||
@@ -395,8 +395,8 @@ export class ZibalService implements IPaymentGateway {
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/request/lazy`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
@@ -436,8 +436,8 @@ export class ZibalService implements IPaymentGateway {
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/verify`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
});
|
||||
@@ -469,14 +469,14 @@ export class ZibalService implements IPaymentGateway {
|
||||
where: {
|
||||
key: {
|
||||
in: [
|
||||
'ZIBAL_EBANK_TOKEN',
|
||||
'zibal_ebank_token',
|
||||
'ZIBAL_API_KEY',
|
||||
'zibal_api_key',
|
||||
'ZIBAL_TOKEN',
|
||||
'zibal_token',
|
||||
'ZIBAL_MERCHANT',
|
||||
'zibal_merchant',
|
||||
"ZIBAL_EBANK_TOKEN",
|
||||
"zibal_ebank_token",
|
||||
"ZIBAL_API_KEY",
|
||||
"zibal_api_key",
|
||||
"ZIBAL_TOKEN",
|
||||
"zibal_token",
|
||||
"ZIBAL_MERCHANT",
|
||||
"zibal_merchant",
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -484,20 +484,20 @@ export class ZibalService implements IPaymentGateway {
|
||||
|
||||
const map = new Map(settings.map((s) => [s.key, s.value?.trim()]));
|
||||
const token =
|
||||
map.get('ZIBAL_EBANK_TOKEN') ||
|
||||
map.get('zibal_ebank_token') ||
|
||||
map.get('ZIBAL_API_KEY') ||
|
||||
map.get('zibal_api_key') ||
|
||||
map.get('ZIBAL_TOKEN') ||
|
||||
map.get('zibal_token');
|
||||
map.get("ZIBAL_EBANK_TOKEN") ||
|
||||
map.get("zibal_ebank_token") ||
|
||||
map.get("ZIBAL_API_KEY") ||
|
||||
map.get("zibal_api_key") ||
|
||||
map.get("ZIBAL_TOKEN") ||
|
||||
map.get("zibal_token");
|
||||
|
||||
if (token && token.length > 0 && token !== 'zibal') {
|
||||
if (token && token.length > 0 && token !== "zibal") {
|
||||
return token;
|
||||
}
|
||||
|
||||
// If token not set, check merchant if it's a real merchant key (not sandbox 'zibal')
|
||||
const merchant = map.get('ZIBAL_MERCHANT') || map.get('zibal_merchant');
|
||||
if (merchant && merchant.length > 0 && merchant !== 'zibal') {
|
||||
const merchant = map.get("ZIBAL_MERCHANT") || map.get("zibal_merchant");
|
||||
if (merchant && merchant.length > 0 && merchant !== "zibal") {
|
||||
return merchant;
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -509,13 +509,13 @@ export class ZibalService implements IPaymentGateway {
|
||||
process.env.ZIBAL_API_KEY ||
|
||||
process.env.ZIBAL_TOKEN ||
|
||||
process.env.ZIBAL_MERCHANT ||
|
||||
''
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
private async apiRequest<T>(
|
||||
endpoint: string,
|
||||
method: 'GET' | 'POST' = 'POST',
|
||||
method: "GET" | "POST" = "POST",
|
||||
body?: Record<string, any>,
|
||||
): Promise<T> {
|
||||
const token = await this.getAccessToken();
|
||||
@@ -523,22 +523,22 @@ export class ZibalService implements IPaymentGateway {
|
||||
const apiKey = token || merchant;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
// Zibal API accepts Bearer Token in Authorization header
|
||||
if (token && token !== 'zibal') {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
if (token && token !== "zibal") {
|
||||
headers["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Prepare JSON body: ensure apiKey / merchant is correctly passed
|
||||
const finalBody =
|
||||
body && method === 'POST'
|
||||
body && method === "POST"
|
||||
? {
|
||||
...body,
|
||||
// Ensure apiKey is set if not already present
|
||||
apiKey:
|
||||
body.apiKey || (token && token !== 'zibal' ? token : apiKey),
|
||||
body.apiKey || (token && token !== "zibal" ? token : apiKey),
|
||||
}
|
||||
: body;
|
||||
|
||||
@@ -573,14 +573,14 @@ export class ZibalService implements IPaymentGateway {
|
||||
* لیست کیف پولهای متصل در زیبال
|
||||
*/
|
||||
async getWalletList() {
|
||||
return this.apiRequest<any>('/v1/wallet/list', 'GET');
|
||||
return this.apiRequest<any>("/v1/wallet/list", "GET");
|
||||
}
|
||||
|
||||
/**
|
||||
* استعلام موجودی یک کیف پول مشخص
|
||||
*/
|
||||
async getWalletBalance(walletId: number) {
|
||||
return this.apiRequest<any>('/v1/wallet/balance', 'POST', { id: walletId });
|
||||
return this.apiRequest<any>("/v1/wallet/balance", "POST", { id: walletId });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -597,7 +597,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
const merchant = await this.getMerchant();
|
||||
const accountIdSetting = (
|
||||
await this.prisma.uiText.findUnique({
|
||||
where: { key: 'ZIBAL_EBANK_ACCOUNT_ID' },
|
||||
where: { key: "ZIBAL_EBANK_ACCOUNT_ID" },
|
||||
})
|
||||
)?.value;
|
||||
|
||||
@@ -608,15 +608,15 @@ export class ZibalService implements IPaymentGateway {
|
||||
tryReverse: options.tryReverse ?? false,
|
||||
amount: options.amount ? Number(options.amount) : undefined,
|
||||
cardNumber: options.cardNumber || undefined,
|
||||
description: options.description || 'استرداد وجه سفارش در کنینا',
|
||||
description: options.description || "استرداد وجه سفارش در کنینا",
|
||||
};
|
||||
|
||||
const finalAccountId = options.accountId || accountIdSetting;
|
||||
if (finalAccountId && finalAccountId.trim() !== '') {
|
||||
if (finalAccountId && finalAccountId.trim() !== "") {
|
||||
payload.accountId = finalAccountId.trim();
|
||||
}
|
||||
|
||||
return this.apiRequest<any>('/v1/account/refund', 'POST', payload);
|
||||
return this.apiRequest<any>("/v1/account/refund", "POST", payload);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -627,7 +627,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
transactionTrackId?: number | string;
|
||||
}) {
|
||||
const merchant = await this.getMerchant();
|
||||
return this.apiRequest<any>('/v1/account/refund/inquiry', 'POST', {
|
||||
return this.apiRequest<any>("/v1/account/refund/inquiry", "POST", {
|
||||
merchant: merchant || undefined,
|
||||
merchantId: merchant || undefined,
|
||||
refundId: params.refundId ? Number(params.refundId) : undefined,
|
||||
@@ -649,7 +649,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
toDate?: string;
|
||||
}) {
|
||||
const merchant = await this.getMerchant();
|
||||
return this.apiRequest<any>('/v1/account/refund/list', 'POST', {
|
||||
return this.apiRequest<any>("/v1/account/refund/list", "POST", {
|
||||
merchant: merchant || undefined,
|
||||
merchantId: merchant || undefined,
|
||||
status: filter.status,
|
||||
@@ -679,7 +679,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
verbose?: boolean;
|
||||
}) {
|
||||
const merchantId = filter.merchantId || (await this.getMerchant());
|
||||
return this.apiRequest<any>('/v1/gateway/report/transaction', 'POST', {
|
||||
return this.apiRequest<any>("/v1/gateway/report/transaction", "POST", {
|
||||
merchantId,
|
||||
fromDate: filter.fromDate,
|
||||
toDate: filter.toDate,
|
||||
@@ -706,7 +706,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
transactionTrackId?: number;
|
||||
verbose?: boolean;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/report/checkout', 'POST', {
|
||||
return this.apiRequest<any>("/v1/report/checkout", "POST", {
|
||||
fromDate: filter.fromDate,
|
||||
toDate: filter.toDate,
|
||||
page: filter.page || 1,
|
||||
@@ -720,7 +720,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
* گزارش صف تسویههای در انتظار
|
||||
*/
|
||||
async getCheckoutQueueReport(verbose = true) {
|
||||
return this.apiRequest<any>('/v1/report/checkout/queue', 'POST', {
|
||||
return this.apiRequest<any>("/v1/report/checkout/queue", "POST", {
|
||||
verbose,
|
||||
});
|
||||
}
|
||||
@@ -733,7 +733,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
checkoutRequestId?: string,
|
||||
uniqueCode?: string,
|
||||
) {
|
||||
return this.apiRequest<any>('/v1/report/checkout/inquire', 'POST', {
|
||||
return this.apiRequest<any>("/v1/report/checkout/inquire", "POST", {
|
||||
walletId,
|
||||
checkoutRequestId,
|
||||
uniqueCode,
|
||||
@@ -748,8 +748,8 @@ export class ZibalService implements IPaymentGateway {
|
||||
name: string;
|
||||
callbackUrl?: string;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/subMerchant/create', 'POST', {
|
||||
bankAccount: data.bankAccount.replace(/\s+/g, '').toUpperCase(),
|
||||
return this.apiRequest<any>("/v1/subMerchant/create", "POST", {
|
||||
bankAccount: data.bankAccount.replace(/\s+/g, "").toUpperCase(),
|
||||
name: data.name,
|
||||
callbackUrl: data.callbackUrl,
|
||||
});
|
||||
@@ -759,7 +759,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
* لیست ذینفعهای ثبت شده
|
||||
*/
|
||||
async getSubMerchantList(page = 1, size = 20) {
|
||||
return this.apiRequest<any>('/v1/subMerchant/list', 'POST', { page, size });
|
||||
return this.apiRequest<any>("/v1/subMerchant/list", "POST", { page, size });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -770,7 +770,7 @@ export class ZibalService implements IPaymentGateway {
|
||||
bankAccount: string;
|
||||
name: string;
|
||||
}) {
|
||||
return this.apiRequest<any>('/v1/subMerchant/edit', 'POST', data);
|
||||
return this.apiRequest<any>("/v1/subMerchant/edit", "POST", data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -778,30 +778,30 @@ export class ZibalService implements IPaymentGateway {
|
||||
*/
|
||||
getResultMessage(resultCode: number): string {
|
||||
const messages: Record<number, string> = {
|
||||
1: 'موفق',
|
||||
2: 'API Key به درستی ارسال نشده است',
|
||||
3: 'API Key صحیح نیست',
|
||||
4: 'اجازه دسترسی به این سرویس صادر نشده است',
|
||||
5: 'آدرس callbackUrl نامعتبر است',
|
||||
6: 'مقدار ورودی نامعتبر است',
|
||||
7: 'IP ارسالکننده درخواست نامعتبر است',
|
||||
8: 'API Key غیرفعال است',
|
||||
9: 'حداقل مبلغ باید ۱,۰۰۰ ریال باشد',
|
||||
14: 'درخواست انتقال وجه یا تسویه یافت نشد',
|
||||
21: 'شماره شبای وارد شده معتبر نیست',
|
||||
29: 'موجودی کیفپول کارمزد کافی نیست',
|
||||
44: 'شبای مورد نظر یافت نشد',
|
||||
45: 'سرویسدهندهها برای استعلام در دسترس نیستند',
|
||||
100: 'با موفقیت تایید شد',
|
||||
102: 'merchant یافت نشد',
|
||||
103: 'merchant غیرفعال است',
|
||||
104: 'merchant نامعتبر است',
|
||||
105: 'مبلغ باید بیشتر از ۱,۰۰۰ ریال باشد',
|
||||
106: 'callbackUrl نامعتبر است',
|
||||
113: 'مبلغ تراکنش بیش از سقف مجاز است',
|
||||
201: 'تراکنش قبلا تایید شده است',
|
||||
202: 'سفارش پرداخت نشده یا ناموفق بوده است',
|
||||
203: 'trackId نامعتبر است',
|
||||
1: "موفق",
|
||||
2: "API Key به درستی ارسال نشده است",
|
||||
3: "API Key صحیح نیست",
|
||||
4: "اجازه دسترسی به این سرویس صادر نشده است",
|
||||
5: "آدرس callbackUrl نامعتبر است",
|
||||
6: "مقدار ورودی نامعتبر است",
|
||||
7: "IP ارسالکننده درخواست نامعتبر است",
|
||||
8: "API Key غیرفعال است",
|
||||
9: "حداقل مبلغ باید ۱,۰۰۰ ریال باشد",
|
||||
14: "درخواست انتقال وجه یا تسویه یافت نشد",
|
||||
21: "شماره شبای وارد شده معتبر نیست",
|
||||
29: "موجودی کیفپول کارمزد کافی نیست",
|
||||
44: "شبای مورد نظر یافت نشد",
|
||||
45: "سرویسدهندهها برای استعلام در دسترس نیستند",
|
||||
100: "با موفقیت تایید شد",
|
||||
102: "merchant یافت نشد",
|
||||
103: "merchant غیرفعال است",
|
||||
104: "merchant نامعتبر است",
|
||||
105: "مبلغ باید بیشتر از ۱,۰۰۰ ریال باشد",
|
||||
106: "callbackUrl نامعتبر است",
|
||||
113: "مبلغ تراکنش بیش از سقف مجاز است",
|
||||
201: "تراکنش قبلا تایید شده است",
|
||||
202: "سفارش پرداخت نشده یا ناموفق بوده است",
|
||||
203: "trackId نامعتبر است",
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -816,24 +816,24 @@ export class ZibalService implements IPaymentGateway {
|
||||
getStatusMessage(statusCode: number | string): string {
|
||||
const code = Number(statusCode);
|
||||
const messages: Record<number, string> = {
|
||||
'-1': 'در انتظار پردخت',
|
||||
'-2': 'خطای داخلی درگاه',
|
||||
'1': 'پرداخت شده و تایید شده',
|
||||
'2': 'پرداخت شده اما هنوز تایید نشده',
|
||||
'3': 'تراکنش توسط کاربر لغو شد',
|
||||
'4': 'شماره کارت نامعتبر است',
|
||||
'5': 'موجودی حساب کافی نیست',
|
||||
'6': 'رمز کارت اشتباه است',
|
||||
'7': 'تعداد دفعات ورود رمز غلط بیش از حد مجاز است',
|
||||
'8': 'کارت منقضی شده است',
|
||||
'9': 'مبلغ تراکنش بیش از سقف مجاز کارت است',
|
||||
'10': 'صادرکننده کارت نامعتبر است',
|
||||
'11': 'خطای سوییچ بانک صادرکننده',
|
||||
'12': 'کارت یا حساب مسدود است',
|
||||
'15': 'تراکنش استرداد شده',
|
||||
'16': 'تراکنش در حال استرداد',
|
||||
'18': 'تراکنش ریورس شده',
|
||||
'21': 'پذیرنده نامعتبر است',
|
||||
"-1": "در انتظار پردخت",
|
||||
"-2": "خطای داخلی درگاه",
|
||||
"1": "پرداخت شده و تایید شده",
|
||||
"2": "پرداخت شده اما هنوز تایید نشده",
|
||||
"3": "تراکنش توسط کاربر لغو شد",
|
||||
"4": "شماره کارت نامعتبر است",
|
||||
"5": "موجودی حساب کافی نیست",
|
||||
"6": "رمز کارت اشتباه است",
|
||||
"7": "تعداد دفعات ورود رمز غلط بیش از حد مجاز است",
|
||||
"8": "کارت منقضی شده است",
|
||||
"9": "مبلغ تراکنش بیش از سقف مجاز کارت است",
|
||||
"10": "صادرکننده کارت نامعتبر است",
|
||||
"11": "خطای سوییچ بانک صادرکننده",
|
||||
"12": "کارت یا حساب مسدود است",
|
||||
"15": "تراکنش استرداد شده",
|
||||
"16": "تراکنش در حال استرداد",
|
||||
"18": "تراکنش ریورس شده",
|
||||
"21": "پذیرنده نامعتبر است",
|
||||
};
|
||||
|
||||
return messages[code] || `وضعیت نامشخص (${statusCode})`;
|
||||
|
||||
Reference in new issue
Block a user