Compare commits

...

10 Commits

  1. 1
      migrations/20250104074851-create-user.js
  2. 2
      migrations/20250104094702-create-admin.js
  3. 8
      migrations/20250104112403-create-product.js
  4. 54
      migrations/20250105062732-create-invoice.js
  5. 33
      migrations/20250105063054-create-cart.js
  6. 22
      src/cart/cart.controller.ts
  7. 23
      src/cart/cart.module.ts
  8. 128
      src/cart/cart.service.ts
  9. 2
      src/cart/dto/add-to-cart.dto.ts
  10. 24
      src/cart/entities/cart.entity.ts
  11. 4
      src/config/database.config.ts
  12. 31
      src/invoice/entities/invoice.entity.ts
  13. 14
      src/invoice/invoice.controller.ts
  14. 14
      src/invoice/invoice.module.ts
  15. 77
      src/invoice/invoice.service.ts
  16. 4
      src/main.ts
  17. 72
      src/payment/payment.controller.ts
  18. 4
      src/payment/payment.module.ts
  19. 66
      src/payment/payment.service.ts
  20. 19
      src/wallet/wallet.controller.ts
  21. 1
      src/wallet/wallet.module.ts
  22. 16
      src/wallet/wallet.service.ts

@ -3,6 +3,7 @@
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.dropTable('Users',{cascade:true})
await queryInterface.createTable('Users', {
id: {
allowNull: false,

@ -2,6 +2,8 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Admins', { cascade: true });
await queryInterface.createTable('Admins', {
id: {
allowNull: false,

@ -1,8 +1,10 @@
'use strict';
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Products', {
await queryInterface.dropTable("Products", { cascade: true });
await queryInterface.createTable("Products", {
id: {
type: Sequelize.INTEGER,
allowNull: false,
@ -60,6 +62,6 @@ module.exports = {
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Products');
await queryInterface.dropTable("Products");
},
};

@ -0,0 +1,54 @@
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
const tableExists = await queryInterface
.describeTable("Invoices")
.then(() => true)
.catch(() => false);
if (tableExists) {
await queryInterface.dropTable("Invoices", { cascade: true });
}
await queryInterface.createTable("Invoices", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
userId: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: "Users",
key: "id",
},
onDelete: "CASCADE",
},
totalPaymentAmount: {
type: Sequelize.FLOAT,
allowNull: false,
},
status: {
type: Sequelize.ENUM("pending", "paid"),
allowNull: false,
defaultValue: "pending",
},
createdAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.fn("NOW"),
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.fn("NOW"),
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("Invoices", { cascade: true });
},
};

@ -2,12 +2,13 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("Carts", { cascade: true });
await queryInterface.createTable('Carts', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
userId: {
type: Sequelize.INTEGER,
@ -20,38 +21,44 @@ module.exports = {
},
productId: {
type: Sequelize.INTEGER,
allowNull: false,
allowNull: true,
references: {
model: 'Products',
key: 'id',
},
onDelete: 'CASCADE',
},
invoiceId: {
type: Sequelize.INTEGER,
allowNull: true,
references: {
model: 'Products',
model: 'Invoices',
key: 'id',
},
onDelete: 'CASCADE',
},
quantity: {
type: Sequelize.INTEGER,
allowNull: false,
allowNull: true,
},
productPrice: {
type: Sequelize.DECIMAL(10, 2),
allowNull: false,
},
totalPrice: {
type: Sequelize.DECIMAL(10, 2),
allowNull: false,
allowNull: true,
},
productName: {
type: Sequelize.STRING,
status: {
type: Sequelize.ENUM('open', 'closed'),
allowNull: false,
defaultValue: 'open',
},
createdAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.NOW,
defaultValue: Sequelize.fn('NOW'),
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.NOW,
defaultValue: Sequelize.fn('NOW'),
},
});
},

@ -1,19 +1,21 @@
import { Controller, Get, Post, Patch, Delete, Body, Param, UseGuards, Request } from "@nestjs/common";
import { Controller, Get, Post, Patch, Delete, Body, Param, UseGuards, Request, HttpException, HttpStatus } from "@nestjs/common";
import { CartService } from "./cart.service";
import { JwtAuthGuard } from "src/guard/auth.guard";
import { AddToCartDto } from "./dto/add-to-cart.dto";
import { UpdateCartDto } from "./dto/update-cart.dto";
import { Cart } from "./entities/cart.entity";
import { Invoice } from "src/invoice/entities/invoice.entity";
@Controller("cart")
export class CartController {
constructor(private readonly cartService: CartService) {}
@UseGuards(JwtAuthGuard)
@Post()
async addToCart(@Body() addToCartDto: AddToCartDto, @Request() req: any): Promise<{ message: string; cartItem: Cart }> {
async createAndAddItemToCart(@Body() addToCartDto: AddToCartDto, @Request() req: any): Promise<{ message: string; cartItem: Cart }> {
const userId = req.user.id;
return this.cartService.addToCart({ ...addToCartDto, userId });
return this.cartService.createAndAddItemToCart({ ...addToCartDto, userId });
}
@UseGuards(JwtAuthGuard)
@ -43,4 +45,18 @@ export class CartController {
message: "Product removed from cart successfully",
};
}
@Post(":userId/checkout")
async processOrder(@Param("userId") userId: number, @Body("totalAmount") totalAmount: number): Promise<{ message: string; invoice: Invoice }> {
if (!totalAmount || totalAmount <= 0) {
throw new HttpException("Invalid total amount.", HttpStatus.BAD_REQUEST);
}
try {
const result = await this.cartService.processOrder(userId, totalAmount);
return result;
} catch (error) {
throw new HttpException(error.message || "Order processing failed.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

@ -1,4 +1,4 @@
import { Module } from "@nestjs/common";
import { Module, forwardRef } from "@nestjs/common";
import { CartService } from "./cart.service";
import { CartController } from "./cart.controller";
import { Cart } from "./entities/cart.entity";
@ -7,15 +7,22 @@ import { User } from "src/users/entities/user.entity";
import { Product } from "src/products/entities/product.entity";
import { JwtModule } from "@nestjs/jwt";
import { JwtAuthGuard } from "src/guard/auth.guard";
import { WalletModule } from "src/wallet/wallet.module";
import { InvoiceModule } from "src/invoice/invoice.module";
import { Invoice } from "src/invoice/entities/invoice.entity";
@Module({
imports: [SequelizeModule.forFeature([Cart,User,Product]),
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '1h' },
})
],
imports: [
SequelizeModule.forFeature([Cart, User, Product,Invoice]),
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: "1h" },
}),
WalletModule,
forwardRef(()=>InvoiceModule),
],
controllers: [CartController],
providers: [CartService,JwtAuthGuard],
providers: [CartService, JwtAuthGuard],
exports: [CartService],
})
export class CartModule {}

@ -1,24 +1,27 @@
import { Injectable, HttpException, HttpStatus } from "@nestjs/common";
import { Injectable, HttpException, HttpStatus, Inject, forwardRef } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { Cart } from "./entities/cart.entity";
import { CartResponse } from "./cart.response";
import { User } from "src/users/entities/user.entity";
import { Product } from "src/products/entities/product.entity";
import { console } from "inspector";
import { WalletService } from "src/wallet/wallet.service";
import { InvoiceService } from "src/invoice/invoice.service";
import { Invoice } from "src/invoice/entities/invoice.entity";
@Injectable()
export class CartService {
constructor(
@InjectModel(Cart) private readonly cartModel: typeof Cart,
@InjectModel(Invoice) private readonly invoiceModel: typeof Invoice,
@InjectModel(Product) private readonly productModel: typeof Product,
private readonly walletService: WalletService,
@Inject(forwardRef(() => InvoiceService))
private invoiceService: InvoiceService,
) {}
// Add product to cart
async addToCart(addToCartDto: { userId: number; productId: number; quantity: number }): Promise<{ message: string; cartItem: Cart }> {
//create a cart and add item to cart
async createAndAddItemToCart(addToCartDto: { userId: number; productId: number; quantity: number }): Promise<{ message: string; cartItem: Cart }> {
const { userId, productId, quantity } = addToCartDto;
if (!userId || !productId || !quantity) {
throw new HttpException("Missing required parameters: userId, productId, and quantity are required.", HttpStatus.BAD_REQUEST);
if (!userId || !productId || !quantity || isNaN(Number(quantity)) || Number(quantity) <= 0) {
throw new HttpException("Invalid parameters: userId, productId, and a positive quantity are required.", HttpStatus.BAD_REQUEST);
}
const product = await this.productModel.findByPk(productId);
@ -26,37 +29,49 @@ export class CartService {
throw new HttpException("Product not found!", HttpStatus.NOT_FOUND);
}
const existingCartItem = await this.cartModel.findOne({
where: { userId, productId },
});
if (existingCartItem) {
existingCartItem.quantity += Number(quantity);
existingCartItem.totalPrice = existingCartItem.quantity * existingCartItem.productPrice;
await existingCartItem.save();
return {
message: "Product quantity updated in cart successfully!",
cartItem: existingCartItem,
};
let invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } });
if (!invoice) {
invoice = await this.invoiceService.createInvoiceFromCart(userId);
}
const invoiceId = invoice.id;
let cart = await this.cartModel.findOne({ where: { userId, productId, status: "open" } });
console.log(cart);
if (!cart) {
cart = await this.cartModel.create({
userId,
productId,
invoiceId,
quantity,
productPrice: product.price,
status: "open",
});
await cart.save();
} else {
cart.quantity += Number(quantity);
await cart.save();
}
const newCartItem = await this.cartModel.create({ userId, productId, quantity, productPrice: product.price, totalPrice: product.price * quantity, productName: product.name });
await this.invoiceService.updateTotalPayment(userId);
return {
message: "Product added to cart successfully!",
cartItem: newCartItem,
message: cart.id ? "Product quantity updated in cart successfully!" : "Product added to cart successfully!",
cartItem: cart,
};
}
// Get user's cart
async getUserCart(userId: number): Promise<{ cartItems: Cart[]; totalPrice: number }> {
if (!userId) {
throw new HttpException("User ID is required.", HttpStatus.BAD_REQUEST);
}
const cartItems = await this.cartModel.findAll({
where: { userId },
include: [
{
model: Product,
attributes: ["id", "name", "price", "description", "imageUrl"],
attributes: [],
},
],
});
@ -65,7 +80,7 @@ export class CartService {
throw new HttpException("No cart items found for the specified user.", HttpStatus.NOT_FOUND);
}
const totalPrice = cartItems.reduce((sum, item) => sum + Number(item.totalPrice), 0);
const totalPrice = cartItems.reduce((sum, item) => sum + (Number(item.productPrice * item.quantity) || 0), 0);
return { cartItems, totalPrice };
}
@ -79,20 +94,73 @@ export class CartService {
}
cartItem.quantity = quantity;
cartItem.totalPrice = cartItem.quantity * cartItem.productPrice;
await cartItem.save();
await this.invoiceService.updateTotalPayment(userId);
return cartItem;
}
// Remove product from cart
// Remove an item from cart
async removeFromCart(userId: number, productId: number): Promise<{ message: string }> {
const cartItem = await this.cartModel.findOne({ where: { userId, productId } });
if (!cartItem) {
throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND);
}
await cartItem.destroy();
await this.invoiceService.updateTotalPayment(userId);
return { message: "Item deleted from your cart successfully." };
}
//delete whole cart
async clearCart(userId: number): Promise<void> {
await this.cartModel.destroy({ where: { userId } });
}
//order(clearCart disable)
async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoice: Invoice }> {
try {
const cart = await this.cartModel.findOne({ where: { userId } });
if (!cart) {
throw new HttpException("Cart not found for this user.", HttpStatus.NOT_FOUND);
}
// Deducting credit from wallet
await this.walletService.processPayment(userId, totalAmount);
// Retrieve cart items
const cartItems = await this.cartModel.findAll({ where: { userId } });
if (cartItems.length === 0) {
throw new HttpException("Cart is empty.", HttpStatus.BAD_REQUEST);
}
// Process each cart item and update stock
for (const cartItem of cartItems) {
const { productId, quantity } = cartItem;
const product = await this.productModel.findOne({ where: { id: productId } });
if (!product) {
throw new HttpException(`Product with ID ${productId} not found.`, HttpStatus.NOT_FOUND);
}
if (product.quantity < quantity) {
throw new HttpException(`Insufficient stock for product ID ${productId}.`, HttpStatus.BAD_REQUEST);
}
product.quantity -= quantity; // Reduce stock
await product.save();
}
// Create the invoices for all cart
const invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } });
return { message: "Order processed successfully", invoice };
} catch (error) {
console.log(error);
if (error instanceof HttpException) {
throw error;
} else {
throw new HttpException(`An error occurred while processing the order: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
}

@ -8,6 +8,6 @@ export class AddToCartDto {
@IsInt()
@IsNotEmpty()
@Min(0)
@Min(1)
quantity: number;
}

@ -1,6 +1,7 @@
import { Model, Table, Column, ForeignKey, BelongsTo, DataType } from "sequelize-typescript";
import { User } from "../../users/entities/user.entity";
import { Product } from "../../products/entities/product.entity";
import { Invoice } from "src/invoice/entities/invoice.entity";
@Table
export class Cart extends Model<Cart> {
@ -18,28 +19,29 @@ export class Cart extends Model<Cart> {
@BelongsTo(() => Product, { onDelete: "CASCADE" })
product: Product;
@ForeignKey(() => Invoice)
@Column
invoiceId: number;
@BelongsTo(() => Invoice, { onDelete: "CASCADE" })
invoice: Invoice;
@Column({
type: DataType.INTEGER,
allowNull: false,
allowNull: true,
})
quantity: number;
@Column({
type: DataType.DECIMAL(10, 2),
allowNull: false,
allowNull: true,
})
productPrice: number;
@Column({
type: DataType.DECIMAL(10, 2),
type: DataType.ENUM("open", "closed"),
allowNull: false,
defaultValue: "open",
})
totalPrice: number;
@Column({
type: DataType.STRING,
allowNull: false,
})
productName: string;
status: "open" | "closed";
}

@ -12,6 +12,6 @@ export const databaseConfig: SequelizeModuleOptions = {
password: process.env.DATABASE_PASSWORD || "password",
database: process.env.DATABASE_NAME || "ecommerce",
models: [path.join(__dirname, "../**/entities/*.entity.ts")],
autoLoadModels: true,
synchronize: true,
autoLoadModels: true,
synchronize:true,
};

@ -1,6 +1,14 @@
import { Table, Model, Column, BelongsTo, ForeignKey } from "sequelize-typescript";
import {
Table,
Column,
ForeignKey,
BelongsTo,
DataType,
Model,
HasMany,
} from "sequelize-typescript";
import { User } from "../../users/entities/user.entity";
import { Product } from "../../products/entities/product.entity";
import { Cart } from "src/cart/entities/cart.entity";
@Table
export class Invoice extends Model<Invoice> {
@ -8,9 +16,22 @@ export class Invoice extends Model<Invoice> {
@Column
userId: number;
@BelongsTo(() => User, { onDelete: 'CASCADE' })
@BelongsTo(() => User, { onDelete: "CASCADE" })
user: User;
@Column
totalAmount: number;
@HasMany(() => Cart)
carts: Cart[];
@Column({
type: DataType.FLOAT,
allowNull: false,
})
totalPaymentAmount: number;
@Column({
type: DataType.ENUM("pending", "paid"),
allowNull: false,
defaultValue: "pending",
})
status: string;
}

@ -1,17 +1,11 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from "@nestjs/common";
import { InvoiceService } from "./invoice.service";
import { Invoice } from "./entities/invoice.entity";
@Controller("invoice")
export class InvoiceController {
constructor(private readonly invoiceService: InvoiceService) {}
@Post("create")
async createInvoice(@Body() body: { userId: number; totalAmount: number }): Promise<Invoice> {
const { userId, totalAmount } = body;
return this.invoiceService.createInvoice(userId, totalAmount);
}
@Get(":userId")
async getInvoices(@Param("userId") userId: number): Promise<any> {
return this.invoiceService.getInvoicesByUser(userId);
}
// @Get(":userId")
// async getInvoices(@Param("userId") userId: number): Promise<any> {
// return this.invoiceService.getInvoicesByUser(userId);
// }
}

@ -1,12 +1,14 @@
import { Module } from '@nestjs/common';
import { InvoiceService } from './invoice.service';
import { InvoiceController } from './invoice.controller';
import { SequelizeModule } from '@nestjs/sequelize';
import { Invoice } from './entities/invoice.entity';
import { Module, forwardRef } from "@nestjs/common";
import { SequelizeModule } from "@nestjs/sequelize";
import { InvoiceController } from "./invoice.controller";
import { InvoiceService } from "./invoice.service";
import { Invoice } from "./entities/invoice.entity";
import { CartModule } from "src/cart/cart.module";
@Module({
imports : [SequelizeModule.forFeature([Invoice])],
imports: [SequelizeModule.forFeature([Invoice]), forwardRef(()=>CartModule)],
controllers: [InvoiceController],
providers: [InvoiceService],
exports: [InvoiceService],
})
export class InvoiceModule {}

@ -1,52 +1,71 @@
import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { forwardRef, HttpException, HttpStatus, Inject, Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { Invoice } from "./entities/invoice.entity";
import { CartService } from "src/cart/cart.service";
import { User } from "src/users/entities/user.entity";
import { where } from "sequelize";
@Injectable()
export class InvoiceService {
constructor(@InjectModel(Invoice) private readonly invoiceModel: typeof Invoice) {}
constructor(
@InjectModel(Invoice) private readonly invoiceModel: typeof Invoice,
@Inject(forwardRef(() => CartService))
private cartService: CartService,
) {}
async createInvoice(userId: number, totalAmount: number): Promise<Invoice> {
try {
if (!userId) {
throw new HttpException("User id not found!", HttpStatus.BAD_REQUEST);
}
const newInvoice = await this.invoiceModel.create({ userId, totalAmount });
return newInvoice;
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException("An error occurred while creating the invoice.", HttpStatus.INTERNAL_SERVER_ERROR);
async createInvoiceFromCart(userId: number): Promise<Invoice> {
const user = await User.findByPk(userId);
if (!user) {
throw new HttpException("User not found", HttpStatus.NOT_FOUND);
}
const invoice = await this.invoiceModel.create({
userId,
totalPaymentAmount: 0,
});
return invoice;
}
async updateTotalPayment(userId: number) {
const user = await User.findByPk(userId);
if (!user) {
throw new HttpException("User not found", HttpStatus.NOT_FOUND);
}
const userCartItems = await this.cartService.getUserCart(userId);
if (!userCartItems || !userCartItems.cartItems || userCartItems.cartItems.length === 0) {
throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST);
}
let invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } });
if (!invoice) {
throw new HttpException("Invoice not found", HttpStatus.NOT_FOUND);
}
invoice.totalPaymentAmount = userCartItems.totalPrice;
await invoice.save();
}
async getInvoicesByUser(userId: number): Promise<Invoice[]> {
async getInvoiceByUserAndCart(userId: number): Promise<Invoice> {
try {
if (!userId) {
throw new HttpException('User ID is required.', HttpStatus.BAD_REQUEST);
if (!userId ) {
throw new HttpException("User ID are required.", HttpStatus.BAD_REQUEST);
}
const invoices = await this.invoiceModel.findAll({
where: { userId },
const invoice = await this.invoiceModel.findOne({
where: { userId, status:'pending' },
});
if (!invoices || invoices.length === 0) {
throw new HttpException('No invoices found for this user.', HttpStatus.NOT_FOUND);
if (!invoice) {
throw new HttpException("Invoice not found for this user and cart.", HttpStatus.NOT_FOUND);
}
return invoices;
return invoice;
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException(
'An error occurred while retrieving invoices.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
throw new HttpException("An error occurred while retrieving the invoice.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

@ -1,9 +1,11 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { Sequelize } from 'sequelize-typescript';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const sequelize = app.get(Sequelize);
await sequelize.sync({ alter: true });
app.useGlobalPipes(new ValidationPipe());
await app.listen(process.env.PORT ?? 3000);
}

@ -1,25 +1,59 @@
import { Controller, Get, Query } from '@nestjs/common';
import { PaymentService } from './payment.service';
import { Controller, Post, Body, Param, Get, Query } from "@nestjs/common";
import { PaymentService } from "./payment.service";
import { CartService } from "../cart/cart.service";
import { InvoiceService } from "../invoice/invoice.service";
import { WalletService } from "src/wallet/wallet.service";
@Controller('payment')
@Controller("payment")
export class PaymentController {
constructor(private readonly paymentService: PaymentService) {}
@Get('request')
async requestPayment(){
const amount = 10000;
const description = 'Test payment';
const callbackUrl = 'http://localhost:3000/payment/verify';
const paymentUrl = await this.paymentService.requestPayment(amount, description, callbackUrl);
return { paymentUrl };
constructor(
private readonly wallet: WalletService,
private readonly paymentService: PaymentService,
private readonly cartService: CartService,
) {}
@Post("request/:userId")
async requestPayment(@Param("userId") userId: number): Promise<{ url: string }> {
const userCartItems = await this.cartService.getUserCart(userId);
if (!userCartItems || userCartItems.cartItems.length === 0) {
throw new Error("Cart is empty!");
}
const totalAmount = userCartItems.totalPrice;
const callbackUrl = `http://localhost:3000/payment/verify?userId=${userId}`;
const paymentUrl = await this.paymentService.requestPayment(totalAmount, "Purchase products", callbackUrl);
return { url: paymentUrl };
}
@Get('verify')
async verifyPayment(@Query('Authority') authority: string, @Query('Status') status: string) {
if (status === 'OK') {
const amount = 10000;
const refId = await this.paymentService.verifyPayment(authority, amount);
return { success: true, refId };
} else {
return { success: false, message: 'Payment canceled' };
@Get("verify")
async verifyPayment(@Query() query: { Authority: string; Status: string; userId: number }): Promise<any> {
const { Authority, Status, userId } = query;
if (Status !== "OK") {
throw new Error("Payment failed");
}
if (!userId) {
throw new Error("User ID is required.");
}
try {
const userCartItems = await this.cartService.getUserCart(userId);
if (!userCartItems || userCartItems.cartItems.length === 0) {
throw new Error("Cart is empty!");
}
const totalAmount = userCartItems.totalPrice;
const refId = await this.paymentService.verifyPayment(Authority, totalAmount);
await this.wallet.addBalance(userId,totalAmount)
return { message: "Payment successful", refId};
} catch (error) {
console.log(error)
throw new Error(`Error during payment verification: ${error.message}`);
}
}
}

@ -1,8 +1,12 @@
import { Module } from '@nestjs/common';
import { PaymentService } from './payment.service';
import { PaymentController } from './payment.controller';
import { InvoiceService } from 'src/invoice/invoice.service';
import { CartModule } from 'src/cart/cart.module';
import { WalletModule } from 'src/wallet/wallet.module';
@Module({
imports:[CartModule,WalletModule],
controllers: [PaymentController],
providers: [PaymentService],
})

@ -1,37 +1,55 @@
import { Injectable } from '@nestjs/common';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
const ZarinpalCheckout = require('zarinpal-checkout');
@Injectable()
export class PaymentService {
private zarinpal;
constructor() {
this.zarinpal = ZarinpalCheckout.create('00000000-0000-0000-0000-000000000000', true);
constructor(
) {
this.zarinpal = this.initializeZarinpal();
}
private initializeZarinpal() {
const merchantId = '00000000-0000-0000-0000-000000000000'; // Merchant ID should be valid
const sandboxMode = true;
return ZarinpalCheckout.create(merchantId, sandboxMode);
}
async requestPayment(amount: number, description: string, callbackUrl: string) {
const result = await this.zarinpal.PaymentRequest({
Amount: amount,
CallbackURL: callbackUrl,
Description: description,
});
if (result.status === 100) {
return result.url;
} else {
throw new Error(`Error in payment request: ${result.status}`);
async requestPayment(amount: number, description: string, callbackUrl: string): Promise<string> {
try {
const result = await this.zarinpal.PaymentRequest({
Amount: amount,
CallbackURL: callbackUrl,
Description: description,
});
if (result.status === 100) {
return result.url;
} else {
throw new Error(`Payment request failed with status: ${result.status}`);
}
} catch (error) {
console.log('Error in PaymentRequest:', error);
throw new InternalServerErrorException(`Error in payment request: ${error.message}`);
}
}
async verifyPayment(authority: string, amount: number) {
const result = await this.zarinpal.PaymentVerification({
Amount: amount,
Authority: authority,
});
if (result.status === 100) {
return result.RefID;
} else {
throw new Error(`Payment verification failed: ${result.status}`);
async verifyPayment(authority: string, amount: number): Promise<string> {
try {
const result = await this.zarinpal.PaymentVerification({
Amount: amount,
Authority: authority,
});
if (result.status === 100) {
return result.RefID;
} else {
throw new Error(`Payment verification failed with status: ${result.status}`);
}
} catch (error) {
throw new InternalServerErrorException(`Error in payment verification: ${error.message}`);
}
}
}

@ -1,19 +1,16 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { WalletService } from './wallet.service';
import { AddBalanceResponse } from './add-balance-response.interface';
import { Controller, Get, Post, Body, Patch, Param, Delete } from "@nestjs/common";
import { WalletService } from "./wallet.service";
import { AddBalanceResponse } from "./add-balance-response.interface";
@Controller('wallet')
@Controller("wallet")
export class WalletController {
constructor(private readonly walletService: WalletService) {}
@Get(':userId')
async getBalance(@Param('userId') userId: number): Promise<number> {
@Get(":userId")
async getBalance(@Param("userId") userId: number): Promise<number> {
return this.walletService.getBalance(userId);
}
@Post(':userId/add')
async addBalance(
@Param('userId') userId: number,
@Body('amount') amount: number
): Promise<AddBalanceResponse> {
@Post(":userId/add")
async addBalance(@Param("userId") userId: number, @Body("amount") amount: number): Promise<AddBalanceResponse> {
return this.walletService.addBalance(userId, amount);
}
}

@ -8,5 +8,6 @@ import { SequelizeModule } from '@nestjs/sequelize';
imports: [SequelizeModule.forFeature([Wallet])],
controllers: [WalletController],
providers: [WalletService],
exports: [WalletService],
})
export class WalletModule {}

@ -28,4 +28,20 @@ export class WalletService {
throw new HttpException("An error occurred while adding balance to the wallet.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
async processPayment(userId: number, amount: number): Promise<string> {
const wallet = await this.walletModel.findOne({ where: { userId } });
if (!wallet) {
throw new Error("Wallet not found");
}
if (wallet.balance < amount) {
throw new Error("Insufficient funds");
}
wallet.balance -= amount;
await wallet.save();
return "Payment processed successfully";
}
}

Loading…
Cancel
Save