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