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
async createAndAddItemToCart(addToCartDto: { userId: number; productId: number; quantity: number }): Promise<{ message: string; cartItem: Cart }> {
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();
}
}
const invoiceId = cart.invoiceId;
let existingCartItem = await this.cartModel.findOne({
where: { userId, productId, invoiceId },
});
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);
}
if (existingCartItem) {
existingCartItem.quantity += Number(quantity);
await existingCartItem.save();
const product = await this.productModel.findByPk(productId);
if (!product) {
throw new HttpException("Product not found!", HttpStatus.NOT_FOUND);
}
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;
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,
productId,
invoiceId,
quantity,
productPrice: product.price,
status: "open",
});
return {
message: "Product added to cart successfully!",
cartItem: newCartItem,
};
} 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 cart.save();
} else {
cart.quantity += Number(quantity);
await cart.save();
}
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

@ -3,6 +3,7 @@ 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 {
@ -18,17 +19,37 @@ export class InvoiceService {
throw new HttpException("User not found", HttpStatus.NOT_FOUND);
}
const userCartItems = await this.cartService.getUserCart(userId);
if (!userCartItems || userCartItems.cartItems.length === 0) {
throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST);
}
// const userCartItems = await this.cartService.getUserCart(userId);
// if (!userCartItems || userCartItems.cartItems.length === 0) {
// throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST);
// }
const invoice = await this.invoiceModel.create({
userId,
totalPaymentAmount: userCartItems.totalPrice,
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 getInvoiceByUserAndCart(userId: number): Promise<Invoice> {
try {

Loading…
Cancel
Save