Files
canina/backend/src/payment/payment.service.spec.ts
T
devops 625c3f5ce2
Deploy Canina / deploy (push) Failing after 1m57s
feat(notifications): send branded transactional emails for shop events
Add Canina-branded welcome, contact confirmation/admin notify, and order created/paid/shipped emails via support@canina.ir without blocking the SMS flows.
2026-11-10 13:27:37 +00:00

259 lines
8.4 KiB
TypeScript

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 { TransactionalEmailsService } from "../notifications/transactional-emails.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 },
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
],
}).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" },
});
});
});
});