Refactor order processing structure for better efficiency

master
nicekid1 2 months ago
parent ee10b49cf8
commit d0cb571c40
  1. 46
      src/cart/cart.service.ts

@ -119,22 +119,28 @@ export class CartService {
//order(clearCart disable) //order(clearCart disable)
async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoice: Invoice }> { async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoice: Invoice }> {
try { try {
const cart = await this.cartModel.findOne({ where: { userId } }); const carts = await this.cartModel.findAll({ where: { userId, status: "open" } });
if (!cart) {
throw new HttpException("Cart not found for this user.", HttpStatus.NOT_FOUND); if (!carts || carts.length === 0) {
throw new HttpException("No open carts found for this user.", HttpStatus.NOT_FOUND);
} }
// Deducting credit from wallet let invoice: Invoice | null = null;
await this.walletService.processPayment(userId, totalAmount); for (const cart of carts) {
const invoiceId = cart.invoiceId;
invoice = await this.invoiceModel.findOne({ where: { id: invoiceId, userId } });
// Retrieve cart items if (invoice && invoice.status === "paid") {
const cartItems = await this.cartModel.findAll({ where: { userId } }); return {
if (cartItems.length === 0) { message: `Order for cart ID ${cart.id} has already been processed.`,
throw new HttpException("Cart is empty.", HttpStatus.BAD_REQUEST); invoice,
};
}
} }
// Process each cart item and update stock await this.walletService.processPayment(userId, totalAmount);
for (const cartItem of cartItems) {
for (const cartItem of carts) {
const { productId, quantity } = cartItem; const { productId, quantity } = cartItem;
const product = await this.productModel.findOne({ where: { id: productId } }); const product = await this.productModel.findOne({ where: { id: productId } });
@ -147,15 +153,23 @@ export class CartService {
throw new HttpException(`Insufficient stock for product ID ${productId}.`, HttpStatus.BAD_REQUEST); throw new HttpException(`Insufficient stock for product ID ${productId}.`, HttpStatus.BAD_REQUEST);
} }
product.quantity -= quantity; // Reduce stock product.quantity -= quantity;
await product.save(); await product.save();
} }
// Create the invoices for all cart for (const cart of carts) {
const invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } }); cart.status = "closed";
return { message: "Order processed successfully", invoice }; await cart.save();
}
if (invoice) {
invoice.status = "paid";
await invoice.save();
}
return { message: "Order processed successfully!", invoice };
} catch (error) { } catch (error) {
console.log(error); console.error(error);
if (error instanceof HttpException) { if (error instanceof HttpException) {
throw error; throw error;
} else { } else {

Loading…
Cancel
Save