You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

155 lines
5.4 KiB

import { Injectable, HttpException, HttpStatus, Inject, forwardRef } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { Cart } from "./entities/cart.entity";
import { Product } from "src/products/entities/product.entity";
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(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 }> {
const { userId, productId, quantity } = addToCartDto;
if (!userId || !productId || !quantity) {
throw new HttpException("Missing required parameters: userId, productId, and quantity are required.", HttpStatus.BAD_REQUEST);
}
const product = await this.productModel.findByPk(productId);
if (!product) {
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,
};
}
const newCartItem = await this.cartModel.create({ userId, productId, quantity, productPrice: product.price, totalPrice: product.price * quantity, productName: product.name });
return {
message: "Product added to cart successfully!",
cartItem: newCartItem,
};
}
// 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"],
},
],
});
if (!cartItems || cartItems.length === 0) {
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), 0);
return { cartItems, totalPrice };
}
// Update cart item quantity
async updateCart(userId: number, productId: number, quantity: number): Promise<Cart> {
const cartItem = await this.cartModel.findOne({ where: { userId, productId } });
if (!cartItem) {
throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND);
}
cartItem.quantity = quantity;
cartItem.totalPrice = cartItem.quantity * cartItem.productPrice;
await cartItem.save();
return cartItem;
}
// 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();
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 unable)
async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoice: Invoice }> {
try {
// 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 invoice after processing the cart
const invoice = await this.invoiceService.createInvoiceFromCart(userId);
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);
}
}
}
}