Refactor createAndAddItemToCart method for better structure

master
nicekid1 2 months ago
parent c5c334692d
commit 548f161f7c
  1. 95
      src/cart/cart.service.ts
  2. 31
      src/invoice/invoice.service.ts

@ -19,84 +19,45 @@ export class CartService {
//create a cart and add item to cart //create a cart and add item to cart
async createAndAddItemToCart(addToCartDto: { userId: number; productId: number; quantity: number }): Promise<{ message: string; cartItem: Cart }> { async createAndAddItemToCart(addToCartDto: { userId: number; productId: number; quantity: number }): Promise<{ message: string; cartItem: Cart }> {
const { userId, productId, quantity } = addToCartDto; const { userId, productId, quantity } = addToCartDto;
try {
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);
if (!product) {
throw new HttpException("Product not found!", HttpStatus.NOT_FOUND);
}
let cart = await this.cartModel.findOne({ where: { userId, productId, status: "open" } });
if (!cart) {
// اگر کارتی برای کاربر و محصول وجود ندارد، ایجاد کنید
cart = await this.cartModel.create({
userId,
productId,
quantity,
productPrice: product.price,
status: "open",
});
// بررسی وجود فاکتور در انتظار
let invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } });
// اگر فاکتور وجود ندارد، ایجاد کنید
if (!invoice) {
invoice = await this.invoiceService.createInvoiceFromCart(userId);
}
// تنظیم `invoiceId` برای کارت و ذخیره
cart.invoiceId = invoice.id;
await cart.save();
} else {
// اگر کارت وجود دارد، بررسی وجود فاکتور مرتبط
let invoice = await this.invoiceService.getInvoiceByUserAndCart(userId);
// اگر فاکتور وجود ندارد، ایجاد کنید
if (!invoice) {
invoice = await this.invoiceService.createInvoiceFromCart(userId);
cart.invoiceId = invoice.id;
await cart.save();
}
}
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 invoiceId = cart.invoiceId; const product = await this.productModel.findByPk(productId);
if (!product) {
let existingCartItem = await this.cartModel.findOne({ throw new HttpException("Product not found!", HttpStatus.NOT_FOUND);
where: { userId, productId, invoiceId }, }
});
if (existingCartItem) {
existingCartItem.quantity += Number(quantity);
await existingCartItem.save();
return { let invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } });
message: "Product quantity updated in cart successfully!", if (!invoice) {
cartItem: existingCartItem, invoice = await this.invoiceService.createInvoiceFromCart(userId);
}; }
} const invoiceId = invoice.id;
const newCartItem = await this.cartModel.create({ let cart = await this.cartModel.findOne({ where: { userId, productId, status: "open" } });
console.log(cart)
if (!cart) {
cart = await this.cartModel.create({
userId, userId,
productId, productId,
invoiceId, invoiceId,
quantity, quantity,
productPrice: product.price, productPrice: product.price,
status: "open",
}); });
await cart.save();
return { } else {
message: "Product added to cart successfully!", cart.quantity += Number(quantity);
cartItem: newCartItem, await cart.save();
};
} catch (error) {
console.error("Error adding product to cart:", error);
throw new HttpException(error.message || "An error occurred while adding the product to the cart.", HttpStatus.INTERNAL_SERVER_ERROR);
} }
await this.invoiceService.updateTotalPayment(userId);
return {
message: cart.id ? "Product quantity updated in cart successfully!" : "Product added to cart successfully!",
cartItem: cart,
};
} }
// Get user's cart // Get user's cart

@ -3,6 +3,7 @@ import { InjectModel } from "@nestjs/sequelize";
import { Invoice } from "./entities/invoice.entity"; import { Invoice } from "./entities/invoice.entity";
import { CartService } from "src/cart/cart.service"; import { CartService } from "src/cart/cart.service";
import { User } from "src/users/entities/user.entity"; import { User } from "src/users/entities/user.entity";
import { where } from "sequelize";
@Injectable() @Injectable()
export class InvoiceService { export class InvoiceService {
@ -18,17 +19,37 @@ export class InvoiceService {
throw new HttpException("User not found", HttpStatus.NOT_FOUND); throw new HttpException("User not found", HttpStatus.NOT_FOUND);
} }
const userCartItems = await this.cartService.getUserCart(userId); // const userCartItems = await this.cartService.getUserCart(userId);
if (!userCartItems || userCartItems.cartItems.length === 0) { // if (!userCartItems || userCartItems.cartItems.length === 0) {
throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST); // throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST);
} // }
const invoice = await this.invoiceModel.create({ const invoice = await this.invoiceModel.create({
userId, userId,
totalPaymentAmount: userCartItems.totalPrice, totalPaymentAmount: 0,
}); });
return invoice; 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 getInvoiceByUserAndCart(userId: number): Promise<Invoice> { async getInvoiceByUserAndCart(userId: number): Promise<Invoice> {
try { try {

Loading…
Cancel
Save