-
i want you to build a frontend that will fully exploit my spring backend : package com.ecommerce.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.ecommerce.filter.JwtAuthFilter; import com.ecommerce.utility.Constants.UserRole; @Configuration @EnableWebSecurity @EnableMethodSecurity public class SecurityConfig { @Autowired private JwtAuthFilter authFilter; @Bean // authentication public UserDetailsService userDetailsService() { return new CustomUserDetailsService(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()) .cors(cors -> cors.disable()) .authorizeHttpRequests( auth -> auth.requestMatchers("/api/user/login", "/api/user/register").permitAll() // this APIs are only accessible by ADMIN .requestMatchers("/api/user/admin/register","/api/user/delete/seller", "/api/order/fetch/all", "/api/category/update", "/api/category/add", "/api/category/delete") .hasAuthority(UserRole.ROLE_ADMIN.value()) // this APIs are only accessible by SELLER .requestMatchers("/api/user/fetch/seller/delivery-person", "/api/user/delete/seller/delivery-person", "/api/product/update/image", "/api/product/update/detail", "/api/product/add", "/api/product/delete", "/api/order/assign/delivery-person", "/api/order/fetch/seller-wise", "/api/product/review/seller", "/api/order/update/delivery-status") .hasAuthority(UserRole.ROLE_SELLER.value()) // this APIs are only accessible by SELLER .requestMatchers("/api/order/add", "/api/order/fetch/user-wise", "/api/cart/update", "/api/cart/add", "/api/cart/fetch", "/api/cart/delete", "/api/product/review/add", "api/order/update/delivery-status") .hasAuthority(UserRole.ROLE_CUSTOMER.value()) // this APIs are only accessible by ADMIN & SELLER .requestMatchers("/api/user/fetch/role-wise", "/api/user/update/status","/api/order/update/delivery-status") .hasAnyAuthority(UserRole.ROLE_ADMIN.value(), UserRole.ROLE_SELLER.value()) .anyRequest() .permitAll()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService()); authenticationProvider.setPasswordEncoder(passwordEncoder()); return authenticationProvider; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { return config.getAuthenticationManager(); } } package com.ecommerce.config; import java.util.Arrays; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; // set up cors configuration @Configuration @EnableWebMvc public class WebConfig { private static final Long MAX_AGE = 3600L; private static final int CORS_FILTER_ORDER = -102; @Bean public FilterRegistrationBean<CorsFilter> corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:3000"); config.setAllowedHeaders(Arrays.asList( HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT)); config.setAllowedMethods(Arrays.asList( HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), HttpMethod.DELETE.name())); config.setMaxAge(MAX_AGE); source.registerCorsConfiguration("/**", config); FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source)); bean.setOrder(CORS_FILTER_ORDER); return bean; } } package com.ecommerce.controller; import com.ecommerce.Model.Cart; import com.ecommerce.Model.Product; import com.ecommerce.Model.User; import com.ecommerce.Repositories.CartRepository; import com.ecommerce.Repositories.ProductRepository; import com.ecommerce.Repositories.UserRepository; import com.ecommerce.exception.CartSaveFailedException; import com.ecommerce.service.CartService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ecommerce.dto.CartRequestDto; import com.ecommerce.dto.CartResponseDto; import com.ecommerce.dto.CommonApiResponse; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("api/cart") @CrossOrigin(origins = "http://localhost:3000") public class CartController { private final Logger LOG = LoggerFactory.getLogger(CartController.class); @Autowired private CartService cartService; @Autowired private UserRepository userService; @Autowired private ProductRepository productService; @PostMapping("/add") public ResponseEntity<CommonApiResponse> addCategory(@RequestBody CartRequestDto request) { LOG.info("Request received for add to cart"); CommonApiResponse response = new CommonApiResponse(); if (request == null || request.getUserId() == 0 || request.getProductId() == 0) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User user = this.userService.getUserById(request.getUserId()); if (user == null) { response.setResponseMessage("Failed to add to cart, Customer not found"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } Product product = this.productService.getProductById(request.getProductId()); if (product == null) { response.setResponseMessage("Failed to add to cart, Product not found"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } if(product.getQuantity() < request.getQuantity()) { response.setResponseMessage("Only "+product.getQuantity()+" Quantity is available!!!"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } Cart cart = new Cart(); cart.setUser(user); cart.setProduct(product); cart.setQuantity(request.getQuantity()); cart.setAddedTime( String.valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli())); Cart savedCart = this.cartService.updateCart(cart); if (savedCart == null) { throw new CartSaveFailedException("Failed to add to Cart"); } response.setResponseMessage("Product Added to Cart Successful"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } @PutMapping("/update") public ResponseEntity<CartResponseDto> updateCart(@RequestBody CartRequestDto request) { LOG.info("Request received for updating the cart"); CartResponseDto response = new CartResponseDto(); if (request == null || request.getId() == 0) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } User user = this.userService.getUserById(request.getUserId()); if (user == null) { response.setResponseMessage("Unauthorized User to update the Cart"); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } Cart cart = this.cartService.getCartById(request.getId()); if (cart == null) { response.setResponseMessage("Cart not found:("); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } try { if (request.getQuantity() == 0) { this.cartService.deleteCart(cart); } else { cart.setQuantity(request.getQuantity()); this.cartService.updateCart(cart); } } catch (Exception e) { throw new CartSaveFailedException("Failed to update the Cart"); } response.setResponseMessage("User Cart Updated Successful"); response.setSuccess(true); return new ResponseEntity<CartResponseDto>(response, HttpStatus.OK); } @DeleteMapping("/delete") public ResponseEntity<CartResponseDto> deleteCart(@RequestBody CartRequestDto request) { LOG.info("Request received for deleting the cart"); CartResponseDto response = new CartResponseDto(); if (request.getId() == 0) { response.setResponseMessage("cart id is missing"); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } User user = this.userService.getUserById(request.getUserId()); if (user == null) { response.setResponseMessage("Unauthorized User to delete the Cart"); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } Cart cart = this.cartService.getCartById(request.getId()); if (cart == null) { response.setResponseMessage("Cart not found"); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } try { this.cartService.deleteCart(cart); } catch (Exception e) { throw new CartSaveFailedException("Failed to delete the Cart"); } response.setResponseMessage("User Cart Updated Successful"); response.setSuccess(true); return new ResponseEntity<CartResponseDto>(response, HttpStatus.OK); } @GetMapping("/fetch") public ResponseEntity<CartResponseDto> fetchUserCart(@RequestParam("userId") int userId) { LOG.info("Request received for fetching the user cart"); CartResponseDto response = new CartResponseDto(); User user = this.userService.getUserById(userId); if (user == null) { response.setResponseMessage("Unauthorized User to fetch the Cart"); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Cart> carts = new ArrayList<>(); carts = this.cartService.findByUser(user); if (carts == null) { response.setResponseMessage("No Products found in Cart"); response.setSuccess(false); return new ResponseEntity<CartResponseDto>(response, HttpStatus.BAD_REQUEST); } response.setTotalCartAmount(calulateTotalAmountFromCart(carts)); response.setCarts(carts); response.setResponseMessage("User Cart Fetched Successful"); response.setSuccess(true); return new ResponseEntity<CartResponseDto>(response, HttpStatus.OK); } private BigDecimal calulateTotalAmountFromCart(List<Cart> carts) { BigDecimal totalAmount = BigDecimal.ZERO; if (CollectionUtils.isEmpty(carts)) { return totalAmount; } for (Cart cart : carts) { BigDecimal cartAmount = cart.getProduct().getPrice().multiply(new BigDecimal(cart.getQuantity())); totalAmount = totalAmount.add(cartAmount); } return totalAmount; } } package com.ecommerce.controller; import com.ecommerce.Model.Product; import com.ecommerce.Repositories.CategoryRepository; import com.ecommerce.Repositories.ProductRepository; import com.ecommerce.exception.CategorySaveFailedException; import com.ecommerce.utility.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ecommerce.dto.CategoryResponseDto; import com.ecommerce.dto.CommonApiResponse; import com.ecommerce.Model.Category; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("api/category") @CrossOrigin(origins = "http://localhost:3000") public class CategoryController { private final Logger LOG = LoggerFactory.getLogger(CategoryController.class); @Autowired private CategoryRepository categoryService; @Autowired private ProductRepository productService; @PostMapping("/add") public ResponseEntity<CommonApiResponse> addCategory(@RequestBody Category category) { LOG.info("Request received for add category"); CommonApiResponse response = new CommonApiResponse(); if (category == null) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } category.setStatus(Constants.CategoryStatus.ACTIVE.value()); Category savedCategory = this.categoryService.addCategory(category); if (savedCategory == null) { throw new CategorySaveFailedException("Failed to add category"); } response.setResponseMessage("Category Added Successful"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } @PutMapping("/update") public ResponseEntity<CommonApiResponse> updateCategory(@RequestBody Category category) { LOG.info("Request received for add category"); CommonApiResponse response = new CommonApiResponse(); if (category == null) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } if (category.getId() == 0) { response.setResponseMessage("missing category Id"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } category.setStatus(Constants.CategoryStatus.ACTIVE.value()); Category savedCategory = this.categoryService.updateCategory(category); if (savedCategory == null) { throw new CategorySaveFailedException("Failed to update category"); } response.setResponseMessage("Category Updated Successful"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } @GetMapping("/fetch/all") public ResponseEntity<CategoryResponseDto> fetchAllCategory() { LOG.info("Request received for fetching all categories"); CategoryResponseDto response = new CategoryResponseDto(); List<Category> categories = new ArrayList<>(); categories = this.categoryService.getCategoriesByStatusIn(Arrays.asList(Constants.CategoryStatus.ACTIVE.value())); if (CollectionUtils.isEmpty(categories)) { response.setResponseMessage("No Categories found"); response.setSuccess(false); return new ResponseEntity<CategoryResponseDto>(response, HttpStatus.OK); } response.setCategories(categories); response.setResponseMessage("Category fetched successful"); response.setSuccess(true); return new ResponseEntity<CategoryResponseDto>(response, HttpStatus.OK); } @DeleteMapping("/delete") public ResponseEntity<CommonApiResponse> deleteCategory(@RequestParam("categoryId") int categoryId) { LOG.info("Request received for deleting category"); CommonApiResponse response = new CommonApiResponse(); if (categoryId == 0) { response.setResponseMessage("missing category Id"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } Category category = this.categoryService.getCategoryById(categoryId); if (category == null) { response.setResponseMessage("category not found"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.INTERNAL_SERVER_ERROR); } List<Product> products = this.productService.getAllProductByCategoryAndStatusIn(category, Arrays.asList(Constants.ProductStatus.ACTIVE.value())); category.setStatus(Constants.CategoryStatus.DEACTIVATED.value()); Category updatedCategory = this.categoryService.updateCategory(category); if (updatedCategory == null) { throw new CategorySaveFailedException("Failed to delete the Category"); } if (!CollectionUtils.isEmpty(products)) { for (Product product : products) { product.setStatus(Constants.ProductStatus.DEACTIVATED.value()); } List<Product> udpatedProducts = this.productService.updateAllProduct(products); if (CollectionUtils.isEmpty(udpatedProducts)) { throw new CategorySaveFailedException("Failed to delete the Category"); } } response.setResponseMessage("Category Deleted Successful"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } } package com.ecommerce.controller; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; import com.ecommerce.Model.Cart; import com.ecommerce.Model.Orders; import com.ecommerce.Model.Product; import com.ecommerce.Model.User; import com.ecommerce.Repositories.CartRepository; import com.ecommerce.Repositories.OrdersRepository; import com.ecommerce.Repositories.ProductRepository; import com.ecommerce.Repositories.UserRepository; import com.ecommerce.exception.OrderSaveFailedException; import com.ecommerce.service.CartService; import com.ecommerce.utility.Constants; import com.ecommerce.utility.Helper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ecommerce.dto.CommonApiResponse; import com.ecommerce.dto.OrderResponseDto; import com.ecommerce.dto.UpdateDeliveryStatusRequest; @RestController @RequestMapping("api/order") @CrossOrigin(origins = "http://localhost:3000") public class OrderController { private final Logger LOG = LoggerFactory.getLogger(CartController.class); @Autowired private CartService cartService; @Autowired private UserRepository userService; @Autowired private ProductRepository productService; @Autowired private OrdersRepository orderService; @PostMapping("/add") public ResponseEntity<CommonApiResponse> placeOrder(@RequestParam("userId") int userId) { LOG.info("Request received for ordering the products from the Cart"); CommonApiResponse response = new CommonApiResponse(); if (userId == 0) { response.setResponseMessage("user id missing"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User user = this.userService.getUserById(userId); if (user == null) { response.setResponseMessage("User not found"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } List<Cart> carts = this.cartService.findByUser(user); if (CollectionUtils.isEmpty(carts)) { response.setResponseMessage("No products found in Cart"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } List<Product> products = new ArrayList<>(); // products to update in db after reducing the quantity String orderTime = String .valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); // Create a map to group cart items by seller Map<User, List<Cart>> cartItemsBySeller = new HashMap<>(); for (Cart cart : carts) { User seller = cart.getProduct().getSeller(); // Check if the seller is already in the map if (!cartItemsBySeller.containsKey(seller)) { cartItemsBySeller.put(seller, new ArrayList<>()); } // Add the cart item to the corresponding seller's list cartItemsBySeller.get(seller).add(cart); } // Generate orders for each seller List<Orders> orders = new ArrayList<>(); for (Map.Entry<User, List<Cart>> entry : cartItemsBySeller.entrySet()) { List<Cart> sellerCartItems = entry.getValue(); // Generate a unique order ID for each seller String orderId = Helper.generateOrderId(); for (Cart cart : sellerCartItems) { if (cart.getProduct().getQuantity() < cart.getQuantity()) { throw new OrderSaveFailedException("Failed to Order, few products are out of stock"); } Orders order = new Orders(); order.setOrderId(orderId); order.setUser(user); order.setOrderTime(orderTime); order.setQuantity(cart.getQuantity()); order.setProduct(cart.getProduct()); order.setStatus(Constants.DeliveryStatus.PENDING.value()); order.setDeliveryStatus(Constants.DeliveryStatus.PENDING.value()); orders.add(order); Product productToUpdate = cart.getProduct(); int quantity = productToUpdate.getQuantity() - cart.getQuantity(); productToUpdate.setQuantity(quantity); products.add(productToUpdate); } } List<Orders> addedOrders = this.orderService.addOrder(orders); if (addedOrders == null) { throw new OrderSaveFailedException("Failed to Order Products"); } try { this.cartService.deleteCarts(carts); } catch (Exception e) { throw new OrderSaveFailedException("Failed to Order Products"); } List<Product> updateProducts = this.productService.updateAllProduct(products); if (updateProducts == null) { throw new OrderSaveFailedException("Failed to Order Products"); } response.setResponseMessage("Order Placed Successful, Check Status in Dashboard!!!"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } @GetMapping("/fetch/all") public ResponseEntity<OrderResponseDto> fetchAllOrders() { LOG.info("Request received for fetching all orders"); OrderResponseDto response = new OrderResponseDto(); List<Orders> orders = new ArrayList<>(); orders = this.orderService.getAllOrders(); if (CollectionUtils.isEmpty(orders)) { response.setResponseMessage("No orders found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } response.setOrders(orders); response.setResponseMessage("Orders fetched successful"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } @GetMapping("/fetch/user-wise") public ResponseEntity<OrderResponseDto> fetchUserOrders(@RequestParam("userId") int userId) { LOG.info("Request received for fetching all orders"); OrderResponseDto response = new OrderResponseDto(); if (userId == 0) { response.setResponseMessage("User Id missing"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } User user = this.userService.getUserById(userId); if (user == null) { response.setResponseMessage("User not found, failed to fetch user orders"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Orders> orders = new ArrayList<>(); orders = this.orderService.getOrdersByUserAndStatusIn(user, Arrays.asList(Constants.DeliveryStatus.PENDING.value(), Constants.DeliveryStatus.DELIVERED.value(), Constants.DeliveryStatus.ON_THE_WAY.value(), Constants.DeliveryStatus.PROCESSING.value())); if (CollectionUtils.isEmpty(orders)) { response.setResponseMessage("No orders found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } response.setOrders(orders); response.setResponseMessage("Orders fetched successful"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK);} @GetMapping("/fetch/seller-wise") public ResponseEntity<OrderResponseDto> fetchSellerOrders(@RequestParam("sellerId") int sellerId) { LOG.info("Request received for fetching all seller orders"); OrderResponseDto response = new OrderResponseDto(); if (sellerId == 0) { response.setResponseMessage("Seller Id missing"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } User seller = this.userService.getUserById(sellerId); if (seller == null) { response.setResponseMessage("Seller not found, failed to fetch seller orders"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Orders> orders = new ArrayList<>(); orders = this.orderService.getOrdersBySellerAndStatusIn(seller, Arrays.asList(Constants.DeliveryStatus.PENDING.value(), Constants.DeliveryStatus.DELIVERED.value(), Constants.DeliveryStatus.ON_THE_WAY.value(), Constants.DeliveryStatus.PROCESSING.value())); if (CollectionUtils.isEmpty(orders)) { response.setResponseMessage("No orders found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } response.setOrders(orders); response.setResponseMessage("Orders fetched successful"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } @GetMapping("/fetch") public ResponseEntity<OrderResponseDto> fetchOrdersByOrderId(@RequestParam("orderId") String orderId) { LOG.info("Request received for fetching all orders"); OrderResponseDto response = new OrderResponseDto(); if (orderId == null) { response.setResponseMessage("Order Id missing"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Orders> orders = new ArrayList<>(); orders = this.orderService.getOrdersByOrderId(orderId); if (CollectionUtils.isEmpty(orders)) { response.setResponseMessage("No orders found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } response.setOrders(orders); response.setResponseMessage("Orders fetched successful"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } @PutMapping("/assign/delivery-person") public ResponseEntity<OrderResponseDto> assignDeliveryPerson(@RequestBody UpdateDeliveryStatusRequest request) { LOG.info("Request received for assigning the delivery person for order"); OrderResponseDto response = new OrderResponseDto(); if (request == null || request.getOrderId() == null || request.getDeliveryId() == 0) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Orders> orders = this.orderService.getOrdersByOrderIdAndStatusIn(request.getOrderId(), Arrays.asList(Constants.DeliveryStatus.PENDING.value(), Constants.DeliveryStatus.DELIVERED.value(), Constants.DeliveryStatus.ON_THE_WAY.value(), Constants.DeliveryStatus.PROCESSING.value())); if (CollectionUtils.isEmpty(orders)) { response.setResponseMessage("no orders by found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } User deliveryPerson = this.userService.getUserById(request.getDeliveryId()); if (deliveryPerson == null) { response.setOrders(orders); response.setResponseMessage("Delivery Person not found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } for (Orders order : orders) { order.setDeliveryPerson(deliveryPerson); order.setDeliveryStatus(Constants.DeliveryStatus.PENDING.value()); } List<Orders> updatedOrders = this.orderService.updateOrders(orders); if (updatedOrders == null) { throw new OrderSaveFailedException("Failed to assign the delivery person for the Order"); } response.setOrders(updatedOrders); response.setResponseMessage("Orders fetched successful"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } @PutMapping("/update/delivery-status") public ResponseEntity<OrderResponseDto> updateDeliveryStatus(@RequestBody UpdateDeliveryStatusRequest request) { LOG.info("Request received for assigning the delivery person for order"); OrderResponseDto response = new OrderResponseDto(); if (request == null || request.getOrderId() == null || request.getDeliveryStatus() == null) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } User deliveryPerson = this.userService.getUserById(request.getDeliveryId()); List<Orders> orders = this.orderService.getOrdersByOrderIdAndStatusIn(request.getOrderId(), Arrays.asList(Constants.DeliveryStatus.PENDING.value(), Constants.DeliveryStatus.DELIVERED.value(), Constants.DeliveryStatus.ON_THE_WAY.value(), Constants.DeliveryStatus.PROCESSING.value())); if (CollectionUtils.isEmpty(orders)) { response.setResponseMessage("no orders by found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } for (Orders order : orders) { order.setStatus(request.getDeliveryStatus()); if (request.getDeliveryStatus().equals(Constants.DeliveryStatus.DELIVERED.value())) { order.setDeliveryStatus(Constants.DeliveryStatus.DELIVERED.value()); } } List<Orders> updatedOrders = this.orderService.updateOrders(orders); if (updatedOrders == null) { throw new OrderSaveFailedException("Failed to update Order delivery status"); } response.setOrders(updatedOrders); response.setResponseMessage("Orders fetched successful"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } @GetMapping("/fetch/delivery-wise") public ResponseEntity<OrderResponseDto> fetchDeliveryOrders(@RequestParam("deliveryPersonId") int deliveryPersonId) { LOG.info("Request received for fetching all delivery orders"); OrderResponseDto response = new OrderResponseDto(); if (deliveryPersonId == 0) { response.setResponseMessage("Delivery Person Id missing"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } User delivery = this.userService.getUserById(deliveryPersonId); if (delivery == null) { response.setResponseMessage("Delivery Person not found, failed to delivery orders"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Orders> orders = new ArrayList<>(); orders = this.orderService.getOrdersByDeliveryPersonAndStatusIn(delivery, Arrays.asList(Constants.DeliveryStatus.PENDING.value(), Constants.DeliveryStatus.DELIVERED.value(), Constants.DeliveryStatus.ON_THE_WAY.value(), Constants.DeliveryStatus.PROCESSING.value())); if (CollectionUtils.isEmpty(orders)) { response.setResponseMessage("No orders found"); response.setSuccess(false); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.BAD_REQUEST); } response.setOrders(orders); response.setResponseMessage("Orders fetched successful"); response.setSuccess(true); return new ResponseEntity<OrderResponseDto>(response, HttpStatus.OK); } @GetMapping("/fetch/delivery-status/all") public ResponseEntity<List<String>> fetchAllDeliveryStatus() { List<String> deliveryStatus = new ArrayList<>(); for (Constants.DeliveryStatus status : Constants.DeliveryStatus.values()) { deliveryStatus.add(status.value()); } return new ResponseEntity<List<String>>(deliveryStatus, HttpStatus.OK); } @GetMapping("/fetch/delivery-time/all") public ResponseEntity<List<String>> fetchAllDeliveryTime() { List<String> deliveryTime = new ArrayList<>(); for (Constants.DeliveryTime time : Constants.DeliveryTime.values()) { deliveryTime.add(time.value()); } return new ResponseEntity<List<String>>(deliveryTime, HttpStatus.OK); } } package com.ecommerce.controller; import com.ecommerce.Model.Category; import com.ecommerce.Model.Product; import com.ecommerce.Model.ProductImage; import com.ecommerce.Model.User; import com.ecommerce.Repositories.CategoryRepository; import com.ecommerce.Repositories.ProductRepository; import com.ecommerce.Repositories.UserRepository; import com.ecommerce.dto.*; import com.ecommerce.exception.ProductSaveFailedException; import com.ecommerce.service.StorageService; import com.ecommerce.utility.Constants; import jakarta.servlet.ServletOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("api/product") @CrossOrigin(origins = "http://localhost:3000") public class ProductController { private final Logger LOG = LoggerFactory.getLogger(ProductController.class); @Autowired private ProductRepository productService; @Autowired private CategoryRepository categoryService; @Autowired private UserRepository userService; @Autowired private StorageService storageService; @PostMapping("add") public ResponseEntity<CommonApiResponse> addProduct(ProductAddRequest productDto) { LOG.info("request received for Product add"); CommonApiResponse response = new CommonApiResponse(); if (productDto == null || productDto.getCategoryId() == 0 || productDto.getSellerId() == 0) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } Product product = ProductAddRequest.toEntity(productDto); product.setStatus(Constants.ProductStatus.ACTIVE.value()); User seller = this.userService.getUserById(productDto.getSellerId()); if (seller == null) { response.setResponseMessage("Seller not found"); response.setSuccess(false); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } Category category = this.categoryService.getCategoryById(productDto.getCategoryId()); if (category == null) { response.setResponseMessage("Category not found"); response.setSuccess(false); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } product.setSeller(seller); product.setCategory(category); product.setThreeDViewUrl(productDto.getThreeDViewUrl()); // ✅ Handle multiple image uploads List<ProductImage> productImages = new ArrayList<>(); if (productDto.getImages() != null) { for (MultipartFile image : productDto.getImages()) { if (image != null && !image.isEmpty()) { String fileName = storageService.store(image); ProductImage pi = new ProductImage(); pi.setImageUrl(fileName); pi.setProduct(product); // important for bidirectional mapping productImages.add(pi); } } } product.setImages(productImages); Product savedProduct = this.productService.addProduct(product); if (savedProduct == null) { throw new ProductSaveFailedException("Failed to save the Product"); } response.setResponseMessage("Product added successful"); response.setSuccess(true); return new ResponseEntity<>(response, HttpStatus.OK); } // ⬇ KEEPING THE REST OF YOUR METHODS UNCHANGED // ... other methods like updateProductDetails(), updateProductDetails (image), // deleteProduct(), fetchProductById(), fetchAllProducts(), // fetchAllSellerProduct(), fetchAllSellerProductAndCategory(), // searchProductsByName(), searchSellerProductsByName(), // fetchAllProductsByCategory(), fetchProductImage() ... } package com.ecommerce.controller; import com.ecommerce.Model.Product; import com.ecommerce.Model.Review; import com.ecommerce.Model.User; import com.ecommerce.Repositories.ProductRepository; import com.ecommerce.Repositories.ReviewRepository; import com.ecommerce.Repositories.UserRepository; import com.ecommerce.exception.ReviewSaveFailedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.ecommerce.dto.AddReviewRequest; import com.ecommerce.dto.CommonApiResponse; import com.ecommerce.dto.ProductReviewResponseDto; import java.text.DecimalFormat; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("api/product/review") @CrossOrigin(origins = "http://localhost:3000") public class ReviewController { private final Logger LOG = LoggerFactory.getLogger(ProductController.class); @Autowired private ProductRepository productService; @Autowired private UserRepository userService; @Autowired private ReviewRepository reviewService; @PostMapping("add") public ResponseEntity<CommonApiResponse> addProductReview(@RequestBody AddReviewRequest request) { LOG.info("request received for adding product review"); CommonApiResponse response = new CommonApiResponse(); if (request == null || request.getUserId() == 0 || request.getProductId() == 0 || request.getStar() == 0 || request.getReview() == null) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User user = this.userService.getUserById(request.getUserId()); if (user == null) { response.setResponseMessage("user not found"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } Product product = this.productService.getProductById(request.getProductId()); if (product == null) { response.setResponseMessage("product not found"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } Review review = new Review(); review.setProduct(product); review.setReview(request.getReview()); review.setStar(request.getStar()); review.setUser(user); Review addedReview = this.reviewService.addReview(review); if (addedReview == null) { throw new ReviewSaveFailedException("Failed to save the review"); } response.setResponseMessage("product review added successful"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } @GetMapping("fetch") public ResponseEntity<ProductReviewResponseDto> fetchProductReview(@RequestParam("productId") int productId) { LOG.info("request received for fetching the product reviews"); ProductReviewResponseDto response = new ProductReviewResponseDto(); if (productId == 0) { response.setResponseMessage("product id missing"); response.setSuccess(false); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.BAD_REQUEST); } Product product = this.productService.getProductById(productId); if (product == null) { response.setResponseMessage("product not found"); response.setSuccess(false); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Review> reviews = this.reviewService.fetchProductReviews(Arrays.asList(product)); if (CollectionUtils.isEmpty(reviews)) { response.setResponseMessage("No product reviews yet"); response.setSuccess(false); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.OK); } double averageRating = averageProductRating(reviews); response.setReviews(reviews); response.setAverageRating(averageRating); response.setResponseMessage("product reviews fetched"); response.setSuccess(true); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.OK); } private double averageProductRating(List<Review> reviews) { int totalReviews = reviews.size(); if (totalReviews == 0) { return 0.0; } // Calculate the sum of all the ratings int sum = 0; for (Review review : reviews) { sum += review.getStar(); } // Calculate the average rating double averageRating = (double) sum / totalReviews; // Format the average rating to one decimal place DecimalFormat df = new DecimalFormat("#.#"); averageRating = Double.parseDouble(df.format(averageRating)); return averageRating; } @GetMapping("seller") public ResponseEntity<ProductReviewResponseDto> fetchSellerReviews(@RequestParam("sellerId") int sellerId) { LOG.info("request received for fetching the seller product reviews"); ProductReviewResponseDto response = new ProductReviewResponseDto(); if (sellerId == 0) { response.setResponseMessage("seller id missing"); response.setSuccess(false); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.BAD_REQUEST); } User seller = this.userService.getUserById(sellerId); if (seller == null) { response.setResponseMessage("seller not found"); response.setSuccess(false); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.BAD_REQUEST); } List<Review> reviews = this.reviewService.fetchSellerProductReview(seller); if (CollectionUtils.isEmpty(reviews)) { response.setResponseMessage("No product reviews yet"); response.setSuccess(false); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.BAD_REQUEST); } response.setReviews(reviews); response.setResponseMessage("product reviews fetched"); response.setSuccess(true); return new ResponseEntity<ProductReviewResponseDto>(response, HttpStatus.OK); } } package com.ecommerce.controller; import com.ecommerce.Model.Shop; import com.ecommerce.Model.User; import com.ecommerce.dto.CommonApiResponse; import com.ecommerce.Repositories.UserRepository; import com.ecommerce.service.ShopService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.List; @RestController @RequestMapping("api/shop") @CrossOrigin(origins = "http://localhost:3000") public class ShopController { @Autowired private ShopService shopService; @Autowired private UserRepository userRepository; @PostMapping("/create") public ResponseEntity<CommonApiResponse> createShop( @RequestPart("shop") Shop shopRequest, @RequestPart(value = "image", required = false) MultipartFile image, @RequestParam int sellerId ) { CommonApiResponse response = new CommonApiResponse(); User seller = userRepository.getUserById(sellerId); if (seller == null || !"seller".equalsIgnoreCase(seller.getRole())) { response.setSuccess(false); response.setResponseMessage("Invalid seller ID or user is not a seller"); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } try { shopRequest.setSeller(seller); Shop createdShop = shopService.createShop(shopRequest, image); if (createdShop == null) { response.setSuccess(false); response.setResponseMessage("Failed to create shop"); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } response.setSuccess(true); response.setResponseMessage("Shop created successfully"); return new ResponseEntity<>(response, HttpStatus.OK); } catch (Exception e) { response.setSuccess(false); response.setResponseMessage("Error creating shop: " + e.getMessage()); return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping("/seller") public ResponseEntity<List<Shop>> getShopsBySeller(@RequestParam int sellerId) { User seller = userRepository.getUserById(sellerId); if (seller == null || !"seller".equalsIgnoreCase(seller.getRole())) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } List<Shop> shops = shopService.getShopsBySeller(seller); return new ResponseEntity<>(shops, HttpStatus.OK); } @GetMapping("/nearby") public ResponseEntity<List<Shop>> getNearbyShops( @RequestParam double latitude, @RequestParam double longitude, @RequestParam double radiusKm) { List<Shop> nearbyShops = shopService.findNearbyShops(latitude, longitude, radiusKm); return new ResponseEntity<>(nearbyShops, HttpStatus.OK); } } package com.ecommerce.controller; import com.ecommerce.Model.Address; import com.ecommerce.Model.Product; import com.ecommerce.Model.User; import com.ecommerce.Repositories.AddressRepository; import com.ecommerce.Repositories.ProductRepository; import com.ecommerce.Repositories.UserRepository; import com.ecommerce.dto.*; import com.ecommerce.exception.UserSaveFailedException; import com.ecommerce.utility.Constants; import com.ecommerce.utility.JwtUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("api/user") @CrossOrigin(origins = "http://localhost:3000") public class UserController { private final Logger LOG = LoggerFactory.getLogger(UserController.class); @Autowired private UserRepository userService; @Autowired private AddressRepository addressService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private AuthenticationManager authenticationManager; @Autowired private ProductRepository productService; @Autowired private JwtUtils jwtUtils; // RegisterUserRequestDto, we will set only email, password & role from UI @PostMapping("/admin/register") public ResponseEntity<CommonApiResponse> registerAdmin(@RequestBody RegisterUserRequestDto registerRequest) { LOG.info("Request received for Register Admin"); CommonApiResponse response = new CommonApiResponse(); if (registerRequest == null) { response.setResponseMessage("user is null"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } if (registerRequest.getEmailId() == null || registerRequest.getPassword() == null) { response.setResponseMessage("missing input"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User existingUser = this.userService.getUserByEmailAndStatus(registerRequest.getEmailId(), Constants.UserStatus.ACTIVE.value()); if (existingUser != null) { response.setResponseMessage("User already register with this Email"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User user = RegisterUserRequestDto.toUserEntity(registerRequest); user.setRole(Constants.UserRole.ROLE_ADMIN.value()); user.setPassword(passwordEncoder.encode(registerRequest.getPassword())); user.setStatus(Constants.UserStatus.ACTIVE.value()); existingUser = this.userService.addUser(user); if (existingUser == null) { response.setResponseMessage("failed to register admin"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } response.setResponseMessage("Admin registered Successfully"); response.setSuccess(true); LOG.info("Response Sent!!!"); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } // for customer and seller register @PostMapping("register") public ResponseEntity<CommonApiResponse> registerUser(@RequestBody RegisterUserRequestDto request) { LOG.info("Received request for register user"); CommonApiResponse response = new CommonApiResponse(); if (request == null) { response.setResponseMessage("user is null"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User existingUser = this.userService.getUserByEmailAndStatus(request.getEmailId(), Constants.UserStatus.ACTIVE.value()); if (existingUser != null) { response.setResponseMessage("User with this Email Id already resgistered!!!"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } if (request.getRole() == null) { response.setResponseMessage("bad request ,Role is missing"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User user = RegisterUserRequestDto.toUserEntity(request); String encodedPassword = passwordEncoder.encode(user.getPassword()); user.setStatus(Constants.UserStatus.ACTIVE.value()); user.setPassword(encodedPassword); // delivery person is for seller, so we need to set Seller if (user.getRole().equals(Constants.UserRole.ROLE_DELIVERY.value())) { User seller = this.userService.getUserById(request.getSellerId()); if (seller == null) { response.setResponseMessage("Seller not found,"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.INTERNAL_SERVER_ERROR); } user.setSeller(seller); } Address address = new Address(); address.setCity(request.getCity()); address.setPostcode(request.getPostcode()); address.setStreet(request.getStreet()); Address savedAddress = this.addressService.addAddress(address); if (savedAddress == null) { throw new UserSaveFailedException("Registration Failed because of Technical issue:("); } user.setAddress(savedAddress); existingUser = this.userService.addUser(user); if (existingUser == null) { throw new UserSaveFailedException("Registration Failed because of Technical issue:("); } response.setResponseMessage("User registered Successfully"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } @PostMapping("login") public ResponseEntity<UserLoginResponse> login(@RequestBody UserLoginRequest loginRequest) { LOG.info("Received request for User Login"); UserLoginResponse response = new UserLoginResponse(); if (loginRequest == null) { response.setResponseMessage("Missing Input"); response.setSuccess(false); return new ResponseEntity<UserLoginResponse>(response, HttpStatus.BAD_REQUEST); } String jwtToken = null; User user = null; List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority(loginRequest.getRole())); try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmailId(), loginRequest.getPassword(), authorities)); } catch (Exception ex) { response.setResponseMessage("Invalid email or password."); response.setSuccess(false); return new ResponseEntity<UserLoginResponse>(response, HttpStatus.BAD_REQUEST); } jwtToken = jwtUtils.generateToken(loginRequest.getEmailId()); user = this.userService.getUserByEmailIdAndRoleAndStatus(loginRequest.getEmailId(), loginRequest.getRole(), Constants.UserStatus.ACTIVE.value()); UserDto userDto = UserDto.toUserDtoEntity(user); // user is authenticated if (jwtToken != null) { response.setUser(userDto); response.setResponseMessage("Logged in sucessful"); response.setSuccess(true); response.setJwtToken(jwtToken); return new ResponseEntity<UserLoginResponse>(response, HttpStatus.OK); } else { response.setResponseMessage("Failed to login"); response.setSuccess(false); return new ResponseEntity<UserLoginResponse>(response, HttpStatus.BAD_REQUEST); } }; @GetMapping("/fetch/role-wise") public ResponseEntity<UserResponseDto> fetchAllUsersByRole(@RequestParam("role") String role) throws JsonProcessingException { UserResponseDto response = new UserResponseDto(); if (role == null) { response.setResponseMessage("missing role"); response.setSuccess(false); return new ResponseEntity<UserResponseDto>(response, HttpStatus.BAD_REQUEST); } List<User> users = new ArrayList<>(); users = this.userService.getUserByRole(role); if (users.isEmpty()) { response.setResponseMessage("No Users Found"); response.setSuccess(false); } List<UserDto> userDtos = new ArrayList<>(); for (User user : users) { UserDto dto = UserDto.toUserDtoEntity(user); if (role.equals(Constants.UserRole.ROLE_DELIVERY.value())) { UserDto sellerDto = UserDto.toUserDtoEntity(user.getSeller()); dto.setSeller(sellerDto); } userDtos.add(dto); } response.setUsers(userDtos); response.setResponseMessage("User Fetched Successfully"); response.setSuccess(true); return new ResponseEntity<UserResponseDto>(response, HttpStatus.OK); } @PutMapping("update/status") public ResponseEntity<CommonApiResponse> updateUserStatus(@RequestBody UserStatusUpdateRequestDto request) { LOG.info("Received request for updating the user status"); CommonApiResponse response = new CommonApiResponse(); if (request == null) { response.setResponseMessage("bad request, missing data"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } if (request.getUserId() == 0) { response.setResponseMessage("bad request, user id is missing"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User user = null; user = this.userService.getUserById(request.getUserId()); user.setStatus(request.getStatus()); User updatedUser = this.userService.updateUser(user); if (updatedUser == null) { throw new UserSaveFailedException("Failed to update the User status"); } response.setResponseMessage("User " + request.getStatus() + " Successfully!!!"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } @DeleteMapping("delete/seller") public ResponseEntity<CommonApiResponse> deleteSeller(@RequestParam("sellerId") int sellerId) { UserResponseDto response = new UserResponseDto(); if (sellerId == 0) { response.setResponseMessage("missing seller id"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } User seller = this.userService.getUserById(sellerId); if (seller == null) { response.setResponseMessage("Seller not found"); response.setSuccess(false); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.BAD_REQUEST); } List<Product> products = new ArrayList<>(); products = this.productService.getAllProductBySellerAndStatusIn(seller, Arrays.asList(Constants.ProductStatus.ACTIVE.value())); seller.setStatus(Constants.UserStatus.DEACTIVATED.value()); User deletedSeller = this.userService.updateUser(seller); // deactivating the seller if (deletedSeller == null) { throw new UserSaveFailedException("Failed to deactivate the seller!!!"); } // deactivating all the listed products by seller if (!products.isEmpty()) { for (Product product : products) { product.setStatus(Constants.ProductStatus.DEACTIVATED.value()); } List<Product> deletedProducts = this.productService.updateAllProduct(products); if (CollectionUtils.isEmpty(deletedProducts)) { throw new UserSaveFailedException("Failed to deactivate the seller!!!"); } } response.setResponseMessage("Seller Deactivated Successful"); response.setSuccess(true); return new ResponseEntity<CommonApiResponse>(response, HttpStatus.OK); } } package com.ecommerce.dto; import lombok.Data; @Data public class AddReviewRequest { private int userId; private int productId; private int star; private String review; } package com.ecommerce.dto; import lombok.Data; @Data public class CartRequestDto { private int id; private int userId; private int productId; private int quantity; } package com.ecommerce.dto; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import com.ecommerce.Model.Cart; import lombok.Data; @Data public class CartResponseDto extends CommonApiResponse { private List<Cart> carts = new ArrayList<>(); private BigDecimal totalCartAmount = BigDecimal.ZERO; } package com.ecommerce.dto; import java.util.ArrayList; import java.util.List; import com.ecommerce.Model.Category; import lombok.Data; @Data public class CategoryResponseDto extends CommonApiResponse { private List<Category> categories = new ArrayList<>(); } package com.ecommerce.filter; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import com.ecommerce.config.CustomUserDetailsService; import com.ecommerce.utility.JwtUtils; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @Component public class JwtAuthFilter extends OncePerRequestFilter { @Autowired private JwtUtils jwtUtils; @Autowired private CustomUserDetailsService userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String authHeader = request.getHeader("Authorization"); String token = null; String username = null; if (authHeader != null && authHeader.startsWith("Bearer ")) { token = authHeader.substring(7); username = jwtUtils.extractUsername(token); // username in token is actually a email } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (jwtUtils.validateToken(token, userDetails)) { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authToken); } } filterChain.doFilter(request, response); } } package com.ecommerce.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @Component public class RequestHeaderInterceptor implements HandlerInterceptor { private final Logger LOG = LoggerFactory.getLogger(RequestHeaderInterceptor.class); // This method is called before the controller's handler method is invoked // You can perform pre-processing here // If you return 'true', the request will continue processing; 'false' will stop // the request public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { LOG.info("preHandle() method invoked"); LOG.info("---------------- Request Start ---------------"); LOG.info("Request URL: " + request.getRequestURI()); LOG.info("Method Type: " + request.getMethod()); return true; } // This method is called after the controller's handler method is invoked but // before rendering the view // You can perform operations after the handler method and before rendering the // view public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // LOG.info("postHandle() method invoked"); HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } // This method is called after the request has been completed // You can perform cleanup or logging here public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { LOG.info("afterCompletion() method invoked"); LOG.info("Request URL: " + request.getRequestURI()); LOG.info("Method Type: " + request.getMethod()); LOG.info("Status: " + response.getStatus()); LOG.info("---------------- Request End ---------------"); HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } } package com.ecommerce.Model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Data; @Data @Entity public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String street; private String city; private int postcode; } package com.ecommerce.Model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import lombok.Data; @Data @Entity public class Cart { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne @JoinColumn(name = "user_id") private User user; @ManyToOne @JoinColumn(name = "product_id") private Product product; private int quantity; private String addedTime; // epoch time } /* * Copyright (c) 2008, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, * or the Eclipse Distribution License v. 1.0 which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause */ // Contributors: // Linda DeMichiel - 2.1 // Linda DeMichiel - 2.0 package jakarta.persistence; import java.lang.annotation.Target; import java.lang.annotation.Retention; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static jakarta.persistence.GenerationType.AUTO; /** * Provides for the specification of generation strategies for the * values of primary keys. * * <p> The <code>GeneratedValue</code> annotation * may be applied to a primary key property or field of an entity or * mapped superclass in conjunction with the {@link Id} annotation. * The use of the <code>GeneratedValue</code> annotation is only * required to be supported for simple primary keys. Use of the * <code>GeneratedValue</code> annotation is not supported for derived * primary keys. * * <pre> * * Example 1: * * @Id * @GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ") * @Column(name="CUST_ID") * public Long getId() { return id; } * * Example 2: * * @Id * @GeneratedValue(strategy=TABLE, generator="CUST_GEN") * @Column(name="CUST_ID") * Long id; * </pre> * * @see Id * @see TableGenerator * @see SequenceGenerator * * @since 1.0 */ @Target ({METHOD, FIELD}) @Retention (RUNTIME) public @interface GeneratedValue { /** * (Optional) The primary key generation strategy * that the persistence provider must use to * generate the annotated entity primary key. */ GenerationType strategy() default AUTO; /** * (Optional) The name of the primary key generator * to use as specified in the {@link SequenceGenerator} * or {@link TableGenerator} annotation. * <p> Defaults to the id generator supplied by persistence provider. */ String generator() default ""; } package com.ecommerce.Model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import lombok.Data; @Data @Entity public class Orders { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String orderId; @ManyToOne @JoinColumn(name = "user_id") private User user; @ManyToOne @JoinColumn(name = "product_id") private Product product; private int quantity; private String orderTime; private String status; // Processing, Delivered, On the Way // this will be for customer // delivery properties // updated by seller @ManyToOne @JoinColumn(name = "delivery_person_id") private User deliveryPerson; //updated by delivery person private String deliveryTime; // Evening, Morning, Afternoon, Night private String deliveryDate; private String deliveryStatus; // Delivered, Pending // this will be for actual delivery status } package com.ecommerce.Model; import jakarta.persistence.*; import lombok.Data; import java.math.BigDecimal; import java.util.List; @Data @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String description; private BigDecimal price; private int quantity; private String status; private String threeDViewUrl; // New field for 3D tour link (e.g. Matterport) @ManyToOne @JoinColumn(name = "category_id") private Category category; @ManyToOne @JoinColumn(name = "seller_user_id") private User seller; @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true) private List<ProductImage> images; // New: multiple images } package com.ecommerce.Model; import jakarta.persistence.*; import lombok.Data; @Data @Entity public class ProductImage { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String imageUrl; // <== Make sure this matches the field used in the controller @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "product_id") private Product product; } package com.ecommerce.Model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import lombok.Data; @Data @Entity public class Review { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne @JoinColumn(name = "product_id") private Product product; @ManyToOne @JoinColumn(name = "user_id") private User user; private int star; // out of 5 private String review; } package com.ecommerce.Model; import jakarta.persistence.*; import lombok.Data; @Data @Entity public class Shop { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String description; private String email; private String phone; private String city; private String street; private String postcode; private double latitude; private double longitude; private String status; private String imagePath; // New field @ManyToOne @JoinColumn(name = "seller_id") private User seller; } package com.ecommerce.Model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Entity public class Upload { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String fileName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } } package com.ecommerce.Model; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; import lombok.Data; import java.util.List; @Data @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String firstName; private String lastName; private String emailId; @JsonIgnore private String password; private String phoneNo; private String role; private String status; @OneToOne @JoinColumn(name = "address_id") private Address address; @ManyToOne @JoinColumn(name = "seller_id") private User seller; @OneToMany(mappedBy = "seller", cascade = CascadeType.ALL, orphanRemoval = true) @JsonIgnore private List<Shop> shops; } package com.ecommerce.Repositories; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.ecommerce.Model.Address; @Repository @Service public interface AddressRepository extends JpaRepository<Address, Integer> { default Address addAddress(Address address) { return save(address); } default Address updateAddress(Address address) { return save(address); } default Address getAddressById(int addressId) { return findById(addressId).orElse(null); } } package com.ecommerce.Repositories; import com.ecommerce.Model.Cart; import com.ecommerce.Model.User; import com.ecommerce.Repositories.CartRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Repository @Service public interface CartRepository extends JpaRepository<Cart, Integer> { List<Cart> findByUser(User user); } package com.ecommerce.Repositories; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.ecommerce.Model.Category; @Repository @Service public interface CategoryRepository extends JpaRepository<Category, Integer> { List<Category> findByStatusIn(List<String> status); Long countByStatusIn(List<String> status); default Category addCategory(Category category) { return save(category); } default Category updateCategory(Category category) { return save(category); } default Category getCategoryById(int categoryId) { Optional<Category> optionalCategory = findById(categoryId); return optionalCategory.orElse(null); } default List<Category> getCategoriesByStatusIn(List<String> status) { return findByStatusIn(status); } } package com.ecommerce.Repositories; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.ecommerce.Model.Orders; import com.ecommerce.Model.User; @Repository @Service public interface OrdersRepository extends JpaRepository<Orders, Integer> { List<Orders> findByOrderId(String orderId); List<Orders> findByOrderIdAndStatusIn(String orderId, List<String> status); List<Orders> findByUser(User user); List<Orders> findByUserAndStatusIn(User user, List<String> status); @Query ("SELECT o FROM Orders o WHERE o.product.seller = :seller and status In (:status)") List<Orders> findAllOrdersBySellerAndStatusIn(@Param ("seller") User seller, @Param ("status") List<String> status); @Query ("SELECT o FROM Orders o WHERE o.product.seller = :seller And status In (:status) AND o.orderTime BETWEEN :startDate AND :endDate") List<Orders> findBySellerAndStatusAndOrderTime(@Param ("seller") User seller, @Param ("status") List<String> status, @Param ("startDate") String startDate, @Param ("endDate") String endDate); @Query ("SELECT o FROM Orders o WHERE status In (:status) AND o.orderTime BETWEEN :startDate AND :endDate") List<Orders> findByStatusAndOrderTime(@Param ("status") List<String> status, @Param ("startDate") String startDate, @Param ("endDate") String endDate); @Query ("SELECT o FROM Orders o WHERE status In (:status) AND o.deliveryPerson = :deliveryPerson") List<Orders> findByStatusAndDeliveryPerson(@Param ("status") List<String> status, @Param ("deliveryPerson") User deliveryPerson); default List<Orders> addOrder(List<Orders> orders) { return saveAll(orders); } default List<Orders> updateOrders(List<Orders> orders) { return saveAll(orders); } default List<Orders> getOrdersByOrderId(String orderId) { return findByOrderId(orderId); } default Orders getOrderById(int orderId) { return findById(orderId).orElse(null); } default List<Orders> getOrdersByUser(User user) { return findByUser(user); } default Orders updateOrder(Orders order) { return save(order); } default List<Orders> getOrdersByOrderIdAndStatusIn(String orderId, List<String> status) { return findByOrderIdAndStatusIn(orderId, status); } default List<Orders> getOrdersByUserAndStatusIn(User user, List<String> status) { return findByUserAndStatusIn(user, status); } default List<Orders> getOrdersBySellerAndStatusIn(User seller, List<String> status) { return findAllOrdersBySellerAndStatusIn(seller, status); } default List<Orders> getAllOrders() { return findAll(); } default List<Orders> getOrdersByDeliveryPersonAndStatusIn(User deliveryPerson, List<String> status) { return findByStatusAndDeliveryPerson(status, deliveryPerson); } } package com.ecommerce.Repositories; import com.ecommerce.Model.ProductImage; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ProductImageRepository extends JpaRepository<ProductImage, Integer> { List<ProductImage> findByProductId(int productId); } package com.ecommerce.Repositories; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.ecommerce.Model.Category; import com.ecommerce.Model.Product; import com.ecommerce.Model.User; @Repository @Service public interface ProductRepository extends JpaRepository<Product, Integer> { List<Product> findByStatusIn(List<String> status); List<Product> findBySellerAndStatusIn(User seller, List<String> status); List<Product> findBySellerAndCategoryAndAndStatusIn(User seller, Category category, List<String> status); List<Product> findByCategoryAndStatusIn(Category category, List<String> status); List<Product> findByNameContainingIgnoreCaseAndStatusIn(String productName, List<String> status); List<Product> findByNameContainingIgnoreCaseAndSellerAndStatusIn(String productName, User seller, List<String> status); default Product addProduct(Product product) { return save(product); } default Product updateProduct(Product product) { return save(product); } default Product getProductById(int productId) { Optional<Product> optionalProduct = findById(productId); return optionalProduct.orElse(null); } default List<Product> getAllProductByStatusIn(List<String> status) { return findByStatusIn(status); } default Long countByStatusIn(List<String> status) { return countByStatusIn(status); } default Long countByStatusInAndSeller(List<String> status, User seller) { return countByStatusInAndSeller(status, seller); } default List<Product> getAllProductBySellerAndStatusIn(User seller, List<String> status) { return findBySellerAndStatusIn(seller, status); } default List<Product> getAllProductBySellerAndCategoryAndStatusIn(User seller, Category category, List<String> status) { return findBySellerAndCategoryAndAndStatusIn(seller, category, status); } default List<Product> updateAllProduct(List<Product> products) { return saveAll(products); } default List<Product> getAllProductByCategoryAndStatusIn(Category category, List<String> status) { return findByCategoryAndStatusIn(category, status); } default List<Product> searchProductNameAndStatusIn(String productName, List<String> status) { return findByNameContainingIgnoreCaseAndStatusIn(productName, status); } default List<Product> searchProductNameAndSellerAndStatusIn(String productName, User seller, List<String> status) { return findByNameContainingIgnoreCaseAndSellerAndStatusIn(productName, seller, status); } } package com.ecommerce.Repositories; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.ecommerce.Model.Product; import com.ecommerce.Model.Review; import com.ecommerce.Model.User; @Repository @Service public interface ReviewRepository extends JpaRepository<Review, Integer> { List<Review> findByProductIn(List<Product> products); @Query ("SELECT r FROM Review r WHERE r.product.seller = :seller") List<Review> findAllOrdersBySeller(@Param ("seller") User seller); default Review addReview(Review review) { return save(review); } default List<Review> fetchProductReviews(List<Product> products) { return findByProductIn(products); } default List<Review> fetchSellerProductReview(User seller) { return findAllOrdersBySeller(seller); } } package com.ecommerce.Repositories; import com.ecommerce.Model.Shop; import com.ecommerce.Model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ShopRepository extends JpaRepository<Shop, Integer> { List<Shop> findBySeller(User seller); } package com.ecommerce.Repositories; import com.ecommerce.Model.Upload; import org.springframework.data.repository.CrudRepository; public interface UploadRepo extends CrudRepository<Upload, Long> { } package com.ecommerce.Repositories; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.ecommerce.Model.User; @Repository @Service public interface UserRepository extends JpaRepository<User, Integer> { User findByEmailId(String email); User findByEmailIdAndStatus(String email, String status); User findByRoleAndStatusIn(String role, List<String> status); List<User> findByRole(String role); List<User> findBySellerAndRole(User seller, String role); List<User> findBySellerAndRoleAndStatusIn(User seller, String role, List<String> status); User findByEmailIdAndRoleAndStatus(String emailId, String role, String status); List<User> findByRoleAndStatus(String role, String status); default User addUser(User user) { return save(user); } default User updateUser(User user) { return save(user); } default User getUserByEmailAndStatus(String emailId, String status) { return findByEmailIdAndStatus(emailId, status); } default User getUserByEmailId(String emailId) { return findByEmailId(emailId); } default List<User> getUserByRole(String role) { return findByRole(role); } default User getUserById(int userId) { Optional<User> optionalUser = findById(userId); return optionalUser.orElse(null); } default User getUserByEmailIdAndRoleAndStatus(String emailId, String role, String status) { return findByEmailIdAndRoleAndStatus(emailId, role, status); } default List<User> getUserBySellerAndRoleAndStatusIn(User seller, String role, List<String> status) { return findBySellerAndRoleAndStatusIn(seller, role, status); } default List<User> updateAllUser(List<User> users) { return saveAll(users); } default List<User> getUserByRoleAndStatus(String role, String status) { return findByRoleAndStatus(role, status); } } package com.ecommerce.Repositories; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import com.ecommerce.Model.User; @Repository @Service public interface UserRepository extends JpaRepository<User, Integer> { User findByEmailId(String email); User findByEmailIdAndStatus(String email, String status); User findByRoleAndStatusIn(String role, List<String> status); List<User> findByRole(String role); List<User> findBySellerAndRole(User seller, String role); List<User> findBySellerAndRoleAndStatusIn(User seller, String role, List<String> status); User findByEmailIdAndRoleAndStatus(String emailId, String role, String status); List<User> findByRoleAndStatus(String role, String status); default User addUser(User user) { return save(user); } default User updateUser(User user) { return save(user); } default User getUserByEmailAndStatus(String emailId, String status) { return findByEmailIdAndStatus(emailId, status); } default User getUserByEmailId(String emailId) { return findByEmailId(emailId); } default List<User> getUserByRole(String role) { return findByRole(role); } default User getUserById(int userId) { Optional<User> optionalUser = findById(userId); return optionalUser.orElse(null); } default User getUserByEmailIdAndRoleAndStatus(String emailId, String role, String status) { return findByEmailIdAndRoleAndStatus(emailId, role, status); } default List<User> getUserBySellerAndRoleAndStatusIn(User seller, String role, List<String> status) { return findBySellerAndRoleAndStatusIn(seller, role, status); } default List<User> updateAllUser(List<User> users) { return saveAll(users); } default List<User> getUserByRoleAndStatus(String role, String status) { return findByRoleAndStatus(role, status); } } package com.ecommerce.service; import com.ecommerce.Model.Cart; import com.ecommerce.Model.User; import java.util.List; public interface CartService { List<Cart> addToCart(List<Cart> cart); Cart updateCart(Cart cart); void deleteCart(Cart cart); List<Cart> findByUser(User user); Cart getCartById(int cartId); void deleteCarts(List<Cart> cart); } package com.ecommerce.service; import com.ecommerce.Model.Cart; import com.ecommerce.Model.User; import com.ecommerce.Repositories.CartRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CartServiceImpl implements CartService { @Autowired private CartRepository cartDao; @Override public List<Cart> addToCart(List<Cart> cart) { return cartDao.saveAll(cart); } @Override public Cart updateCart(Cart cart) { return cartDao.save(cart); } @Override public void deleteCart(Cart cart) { cartDao.delete(cart); } @Override public List<Cart> findByUser(User user) { return cartDao.findByUser(user); } @Override public Cart getCartById(int cartId) { Optional<Cart> optionalCart = this.cartDao.findById(cartId); if(optionalCart.isPresent()) { return optionalCart.get(); } else { return null; } } @Override public void deleteCarts(List<Cart> carts) { this.cartDao.deleteAll(carts); } } package com.ecommerce.service; import com.ecommerce.Model.Shop; import com.ecommerce.Model.User; import com.ecommerce.Repositories.ShopRepository; import com.ecommerce.utility.HaversineUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Service public class ShopService { @Autowired private ShopRepository shopRepository; private final String uploadDir = "uploads/shops/"; public Shop createShop(Shop shop, MultipartFile imageFile) throws IOException { if (imageFile != null && !imageFile.isEmpty()) { File dir = new File(uploadDir); if (!dir.exists()) dir.mkdirs(); String filePath = uploadDir + System.currentTimeMillis() + "_" + imageFile.getOriginalFilename(); File dest = new File(filePath); imageFile.transferTo(dest); shop.setImagePath(filePath); } return shopRepository.save(shop); } public List<Shop> getShopsBySeller(User seller) { return shopRepository.findBySeller(seller); } public List<Shop> findNearbyShops(double latitude, double longitude, double radiusKm) { List<Shop> allShops = shopRepository.findAll(); return allShops.stream() .filter(shop -> HaversineUtil.distance(latitude, longitude, shop.getLatitude(), shop.getLongitude()) <= radiusKm) .collect(Collectors.toList()); } } package com.ecommerce.service; import java.util.List; import org.springframework.core.io.Resource; import org.springframework.web.multipart.MultipartFile; public interface StorageService { List<String> loadAll(); String store(MultipartFile file); Resource load(String fileName); void delete(String fileName); } package com.ecommerce.service; import java.io.File; import java.io.FileOutputStream; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; @Component public class StorageServiceImpl implements StorageService { @Value("${com.hahshop.image.folder.path}") private String BASEPATH; @Override public List<String> loadAll() { File dirPath = new File(BASEPATH); return Arrays.asList(dirPath.list()); } @Override public String store(MultipartFile file) { String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ext; File filePath = new File(BASEPATH, fileName); try (FileOutputStream out = new FileOutputStream(filePath)) { FileCopyUtils.copy(file.getInputStream(), out); return fileName; } catch (Exception e) { e.printStackTrace(); } return null; } @Override public Resource load(String fileName) { File filePath = new File(BASEPATH, fileName); if (filePath.exists()) return new FileSystemResource(filePath); return null; } @Override public void delete(String fileName) { File filePath = new File(BASEPATH, fileName); if (filePath.exists()) filePath.delete(); } } package com.ecommerce.utility; public class Constants { public enum UserRole { ROLE_CUSTOMER("Customer"), ROLE_ADMIN("Admin"), ROLE_SELLER("Seller"), ROLE_DELIVERY("Delivery"); private String role; private UserRole(String role) { this.role = role; } public String value() { return this.role; } } public enum UserStatus { ACTIVE("Active"), DEACTIVATED("Deactivated"); private String status; private UserStatus(String status) { this.status = status; } public String value() { return this.status; } } public enum DeliveryStatus { CANCELLED("Cancelled"), DELIVERED("Delivered"), ON_THE_WAY("On the Way"), PENDING("Pending"), PROCESSING("Processing"); private String status; private DeliveryStatus(String status) { this.status = status; } public String value() { return this.status; } } public enum DeliveryTime { MORNING("Morning"), AFTERNOON("Afternoon"), EVENING("Evening"), NIGHT("Night"), DEFAULT(""); private String time; private DeliveryTime(String time) { this.time = time; } public String value() { return this.time; } } public enum IsDeliveryAssigned { YES("Yes"), NO("No"); private String isDeliveryAssigned; private IsDeliveryAssigned(String isDeliveryAssigned) { this.isDeliveryAssigned = isDeliveryAssigned; } public String value() { return this.isDeliveryAssigned; } } public enum CategoryStatus { ACTIVE("Active"), DEACTIVATED("Deactivated"); private String status; private CategoryStatus(String status) { this.status = status; } public String value() { return this.status; } } public enum ProductStatus { ACTIVE("Active"), DEACTIVATED("Deactivated"); private String status; private ProductStatus(String status) { this.status = status; } public String value() { return this.status; } } } package com.ecommerce.utility; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class DateTimeUtils { public static String getProperDateTimeFormatFromEpochTime(String epochTimeString) { long epochTimeMillis = Long.parseLong(epochTimeString); Instant instant = Instant.ofEpochMilli(epochTimeMillis); ZoneId zoneId = ZoneId.systemDefault(); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId); // Define the desired date format String dateFormatPattern = "yyyy-MM-dd HH:mm:ss"; // Format LocalDateTime to a specific date format String formattedDateTime = formatLocalDateTime(localDateTime, dateFormatPattern); // Print the formatted date and time System.out.println("Formatted DateTime: " + formattedDateTime); return formattedDateTime; } private static String formatLocalDateTime(LocalDateTime dateTime, String dateFormatPattern) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormatPattern); return dateTime.format(formatter); } } package com.ecommerce.utility; public class HaversineUtil { private static final int EARTH_RADIUS_KM = 6371; /** * Calculate the great-circle distance between two points on the Earth's surface. * * @param lat1 Latitude of the first point in decimal degrees * @param lon1 Longitude of the first point in decimal degrees * @param lat2 Latitude of the second point in decimal degrees * @param lon2 Longitude of the second point in decimal degrees * @return Distance between the two points in kilometers */ public static double distance(double lat1, double lon1, double lat2, double lon2) { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return EARTH_RADIUS_KM * c; } } package com.ecommerce.utility; public class Helper { public static String generateOrderId() { String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz"; StringBuilder sb = new StringBuilder(16); for (int i = 0; i < 16; i++) { int index = (int)(AlphaNumericString.length() * Math.random()); sb.append(AlphaNumericString .charAt(index)); } return sb.toString().toUpperCase(); } } package com.ecommerce.utility; import java.security.Key; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; @Component public class JwtUtils { public static final String SECRET = "5aB3r1P8mNqRvKgY7cZxW9jF2hT6fU0eL4dS1aC3bXwVzE6tR8yH0jM5nQ8pZ2k"; public String extractUsername(String token) { return extractClaim(token, Claims::getSubject); } public Date extractExpiration(String token) { return extractClaim(token, Claims::getExpiration); } public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { final Claims claims = extractAllClaims(token); return claimsResolver.apply(claims); } private Claims extractAllClaims(String token) { return Jwts .parserBuilder() .setSigningKey(getSignKey()) .build() .parseClaimsJws(token) .getBody(); } private Boolean isTokenExpired(String token) { return extractExpiration(token).before(new Date()); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = extractUsername(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } public String generateToken(String userName){ Map<String,Object> claims=new HashMap<>(); return createToken(claims,userName); } private String createToken(Map<String, Object> claims, String userName) { return Jwts.builder() .setClaims(claims) .setSubject(userName) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis()+1000*60*30)) .signWith(getSignKey(), SignatureAlgorithm.HS256).compact(); } private Key getSignKey() { byte[] keyBytes= Decoders.BASE64.decode(SECRET); return Keys.hmacShaKeyFor(keyBytes); } } package com.ecommerce; import com.ecommerce.Repositories.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.boot.autoconfigure.domain.EntityScan; import com.ecommerce.Model.User; import com.ecommerce.utility.Constants.UserRole; import com.ecommerce.utility.Constants.UserStatus; @SpringBootApplication @EntityScan(basePackages = "com.ecommerce.Model") public class EcommerceBackendApplication implements CommandLineRunner { private final Logger LOG = LoggerFactory.getLogger(EcommerceBackendApplication.class); @Autowired private UserRepository userService; @Autowired private PasswordEncoder passwordEncoder; public static void main(String[] args) { SpringApplication.run(EcommerceBackendApplication.class, args); } @Override public void run(String... args) throws Exception { User admin = this.userService.getUserByEmailIdAndRoleAndStatus("demo.admin@demo.com", UserRole.ROLE_ADMIN.value(), UserStatus.ACTIVE.value()); if (admin == null) { LOG.info("Admin not found in system, so adding default admin"); User user = new User(); user.setEmailId("demo.admin@demo.com"); user.setPassword(passwordEncoder.encode("123456")); user.setRole(UserRole.ROLE_ADMIN.value()); user.setStatus(UserStatus.ACTIVE.value()); this.userService.addUser(user); } } } package com.ecommerce.config; import com.ecommerce.Repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import com.ecommerce.Model.User; import com.ecommerce.utility.Constants.UserStatus; @Component public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userService; @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { User user = this.userService.getUserByEmailAndStatus(email, UserStatus.ACTIVE.value()); CustomUserDetails customUserDetails = new CustomUserDetails(user); return customUserDetails; } } package com.ecommerce.config; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.ecommerce.Model.User; public class CustomUserDetails implements UserDetails { private static final long serialVersionUID = 1L; private String email; private String password; private List<GrantedAuthority> authorities; public CustomUserDetails(User user) { email=user.getEmailId(); password=user.getPassword(); authorities = new ArrayList<>(); String[] roles = user.getRole().split(","); for (String role : roles) { authorities.add(new SimpleGrantedAuthority(role)); } } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return email; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } package com.ecommerce.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.ecommerce.interceptor.RequestHeaderInterceptor; // to register interceptor @Configuration public class ApplicationConfig implements WebMvcConfigurer { @Autowired private RequestHeaderInterceptor requestHeaderInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(requestHeaderInterceptor); } } # MySQL Properties spring.datasource.url=jdbc:mysql://localhost:3306/marketplace2 spring.datasource.username=root #enter the correct MySQL Password below spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update springdoc.packagesToScan=com.ecommerce.controller springdoc.pathsToMatch=/api/** # File upload properties <<<<<<< HEAD com.hahshop.image.folder.path=C:/Users/K'LIL/Desktop/New folder (2)/mve/back-end/src/main/resources/images com.onlineshopping.image.folder.path=C:/Users/K'LIL/Desktop/New folder (2)/mve/back-end/src/main/resources/images >>>>>>> c0c16e7db20a54778c14a421356e7b7a44e9be0c spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB - Initial Deployment
-
initial commit