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.
65 lines
2.3 KiB
65 lines
2.3 KiB
import { Controller, Get, Post, Patch, Delete, Body, Param, UseGuards, Request, HttpException, HttpStatus } from "@nestjs/common"; |
|
import { CartService } from "./cart.service"; |
|
import { JwtAuthGuard } from "src/guard/auth.guard"; |
|
import { AddToCartDto } from "./dto/add-to-cart.dto"; |
|
import { UpdateCartDto } from "./dto/update-cart.dto"; |
|
import { Cart } from "./entities/cart.entity"; |
|
import { Invoice } from "src/invoice/entities/invoice.entity"; |
|
|
|
@Controller("cart") |
|
export class CartController { |
|
constructor(private readonly cartService: CartService) {} |
|
|
|
@UseGuards(JwtAuthGuard) |
|
@Post() |
|
async addToCart(@Body() addToCartDto: AddToCartDto, @Request() req: any): Promise<{ message: string; cartItem: Cart }> { |
|
const userId = req.user.id; |
|
return this.cartService.addToCart({ ...addToCartDto, userId }); |
|
} |
|
|
|
@UseGuards(JwtAuthGuard) |
|
@Get() |
|
async getUserCart(@Request() req: any): Promise<{ cartItems: Cart[]; totalPrice: number }> { |
|
const userId = req.user.id; |
|
return this.cartService.getUserCart(userId); |
|
} |
|
|
|
@UseGuards(JwtAuthGuard) |
|
@Patch(":productId") |
|
async updateCart(@Param("productId") productId: number, @Body() updateCartDto: UpdateCartDto, @Request() req: any): Promise<{ message: string; updatedCart: Cart }> { |
|
const userId = req.user.id; |
|
const updatedCart = await this.cartService.updateCart(userId, productId, updateCartDto.quantity); |
|
return { |
|
message: "Cart updated successfully", |
|
updatedCart, |
|
}; |
|
} |
|
|
|
@UseGuards(JwtAuthGuard) |
|
@Delete(":productId") |
|
async removeFromCart(@Param("productId") productId: number, @Request() req: any): Promise<{ message: string }> { |
|
const userId = req.user.id; |
|
await this.cartService.removeFromCart(userId, productId); |
|
return { |
|
message: "Product removed from cart successfully", |
|
}; |
|
} |
|
|
|
@Post(':userId/checkout') |
|
async processOrder( |
|
@Param('userId') userId: number, |
|
@Body('totalAmount') totalAmount: number, |
|
): Promise<{ message: string; invoices: Invoice[] }> { |
|
if (!totalAmount || totalAmount <= 0) { |
|
throw new HttpException('Invalid total amount.', HttpStatus.BAD_REQUEST); |
|
} |
|
|
|
try { |
|
const result = await this.cartService.processOrder(userId, totalAmount); |
|
return result; |
|
} catch (error) { |
|
throw new HttpException(error.message || 'Order processing failed.', HttpStatus.INTERNAL_SERVER_ERROR); |
|
} |
|
} |
|
|
|
}
|
|
|