diff --git a/src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java b/src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java index 4c07638..6b03645 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java +++ b/src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java @@ -4,8 +4,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @SpringBootApplication +@EnableJpaAuditing(auditorAwareRef = "auditAwareImpl") public class SpringBootECommerceRestApiApplication { public static void main(String[] args) { diff --git a/src/main/java/com/manir/springbootecommercerestapi/audit/AuditAwareImpl.java b/src/main/java/com/manir/springbootecommercerestapi/audit/AuditAwareImpl.java new file mode 100644 index 0000000..2ba6d01 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/audit/AuditAwareImpl.java @@ -0,0 +1,15 @@ +package com.manir.springbootecommercerestapi.audit; + +import org.springframework.data.domain.AuditorAware; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +@Component("auditAwareImpl") +public class AuditAwareImpl implements AuditorAware { + @Override + public Optional getCurrentAuditor() { + return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName()); + } +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/config/SecurityConfig.java b/src/main/java/com/manir/springbootecommercerestapi/config/SecurityConfig.java index cb723b4..e2a691e 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/config/SecurityConfig.java +++ b/src/main/java/com/manir/springbootecommercerestapi/config/SecurityConfig.java @@ -48,7 +48,8 @@ protected void configure(HttpSecurity http) throws Exception { //to permit all get request and secure post put and delete methods .antMatchers(HttpMethod.GET, "/api/**").permitAll() //authorize singIn and signUp - .antMatchers("/api/v1/auth/**").permitAll() + .antMatchers("/api/v*/auth/**").permitAll() + .antMatchers(HttpMethod.POST, "/api/v*/contact/**").permitAll() .anyRequest() .authenticated(); diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java index b10c997..b119ef8 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java +++ b/src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java @@ -1,9 +1,15 @@ package com.manir.springbootecommercerestapi.controller; import com.manir.springbootecommercerestapi.dto.CommentDto; +import com.manir.springbootecommercerestapi.model.User; import com.manir.springbootecommercerestapi.service.CommentService; +import com.manir.springbootecommercerestapi.service.CommonService; +import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @@ -13,17 +19,30 @@ @RequestMapping(value = "api/v1/products") public class CommentController { - @Resource + @Autowired private CommentService commentService; + @Autowired + private CommonService commonService; //create comment api + @isAuthenticatedAsAdminOrUser @PostMapping("/{productId}/createComment") - public ResponseEntity createComment(@PathVariable Long productId, + public ResponseEntity createComment(@AuthenticationPrincipal Authentication authentication, + @PathVariable Long productId, @RequestBody CommentDto commentDto){ - CommentDto responseComment = commentService.createComment(productId, commentDto); + User customer = commonService.getCurrentAuthenticatedUser(authentication); + CommentDto responseComment = commentService.createComment(customer, productId, commentDto); return new ResponseEntity<>(responseComment, HttpStatus.CREATED); } + //get comment by user + @isAuthenticatedAsAdminOrUser + @GetMapping("/comment/findByUser") + public List findByUser(@AuthenticationPrincipal Authentication authentication){ + User customer = commonService.getCurrentAuthenticatedUser(authentication); + return commentService.findCommentByCustomer(customer); + } + //get all comments api @GetMapping("/getAllComments") public List getAllComments(){ @@ -58,4 +77,6 @@ public ResponseEntity deleteComment(@PathVariable Long productId, @PathV commentService.deleteComment(productId, commentId); return ResponseEntity.ok("Comment with id: "+commentId+" is successfully:)"); } + + } diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/ContactController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/ContactController.java new file mode 100644 index 0000000..d440aed --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/controller/ContactController.java @@ -0,0 +1,33 @@ +package com.manir.springbootecommercerestapi.controller; + +import com.manir.springbootecommercerestapi.dto.ContactDto; +import com.manir.springbootecommercerestapi.service.ContactService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping(value = "api/v1/contact") +public class ContactController { + @Autowired + private ContactService contactService; + + @PostMapping("/sendMessage") + public ResponseEntity sendMessage(@RequestBody ContactDto contactDto, + HttpServletRequest request){ + ContactDto responseMessage = contactService.sendMessage(contactDto, request); + return new ResponseEntity<>(responseMessage, HttpStatus.CREATED); + } + + //get messages api + @PreAuthorize("hasRole('ADMIN')") + @GetMapping("/allMessages") + public List getAllMessages(){ + return contactService.getMessages(); + } +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/FaqController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/FaqController.java new file mode 100644 index 0000000..4c3ea0a --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/controller/FaqController.java @@ -0,0 +1,57 @@ +package com.manir.springbootecommercerestapi.controller; + +import com.manir.springbootecommercerestapi.dto.FaqDto; +import com.manir.springbootecommercerestapi.service.FaqService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("api/v1/faq") +public class FaqController { + @Autowired + private FaqService faqService; + + //add faq api + @PreAuthorize("hasRole('ADMIN')") + @PostMapping("/addFaq") + public ResponseEntity addFaq(@RequestBody FaqDto faqDto){ + FaqDto addedFaq = faqService.addFaq(faqDto); + return new ResponseEntity<>(addedFaq, HttpStatus.CREATED); + } + //list all faqs api + @PreAuthorize("hasRole('ADMIN')") + @GetMapping("/getAllFaqs") + public List listAllFaqs(){ + List faqs = faqService.listAllFaqs(); + return faqs; + } + + //get faq by id api + @PreAuthorize("hasRole('ADMIN')") + @GetMapping("/{id}") + public ResponseEntity getFaqById(@PathVariable Long id){ + FaqDto faq = faqService.getFaqById(id); + return new ResponseEntity<>(faq, HttpStatus.OK); + } + + //update faq api + @PreAuthorize("hasRole('ADMIN')") + @PutMapping("/updateFaq/{id}") + public ResponseEntity updateFaq(@RequestBody FaqDto faqDto, @PathVariable Long id){ + FaqDto updatedFaq = faqService.updateFaq(faqDto, id); + return new ResponseEntity<>(updatedFaq, HttpStatus.OK); + } + + //delete faq api + @PreAuthorize("hasRole('ADMIN')") + @DeleteMapping("/deleteFaq/{id}") + public ResponseEntity deleteFaq(@PathVariable Long id){ + faqService.deleteFaq(id); + return new ResponseEntity<>("Faq with id: "+id+ " is deleted successfully", HttpStatus.OK); + } +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/OrderController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/OrderController.java index 172436f..302422b 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/OrderController.java +++ b/src/main/java/com/manir/springbootecommercerestapi/controller/OrderController.java @@ -2,20 +2,17 @@ import com.manir.springbootecommercerestapi.dto.OrderDto; import com.manir.springbootecommercerestapi.dto.OrderProductsDto; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; import com.manir.springbootecommercerestapi.model.User; import com.manir.springbootecommercerestapi.repository.UserRepository; +import com.manir.springbootecommercerestapi.service.CommonService; import com.manir.springbootecommercerestapi.service.OrderProductsService; import com.manir.springbootecommercerestapi.service.OrderService; import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -27,55 +24,43 @@ @RequestMapping(value = "api/v1/order") public class OrderController { - @Autowired - private UserRepository userRepository; @Autowired private OrderService orderService; @Autowired private OrderProductsService orderProductsService; + @Autowired + private CommonService commonService; //place order complete order api @isAuthenticatedAsAdminOrUser @PostMapping("/placeOrder") public ResponseEntity placeOrder(@AuthenticationPrincipal Authentication authentication){ - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (!(authentication instanceof AnonymousAuthenticationToken)){ - String currentUserEmail = authentication.getName(); - User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found")); - orderService.placeOrder(customer); - return new ResponseEntity<>("Order placed successfully", HttpStatus.CREATED); - }else{ - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } + User customer = commonService.getCurrentAuthenticatedUser(authentication); + orderService.placeOrder(customer); + return new ResponseEntity<>("Order placed successfully", HttpStatus.CREATED); } //find order by customer api @isAuthenticatedAsAdminOrUser @GetMapping("/findByCustomer") public List listOrdersByCustomer(@AuthenticationPrincipal Authentication authentication){ - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (!(authentication instanceof AnonymousAuthenticationToken)){ - String currentUserEmail = authentication.getName(); - User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found")); - List customerOrders = orderService.listOrdersByCustomer(customer); - return customerOrders; - }else{ - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } + + User customer = commonService.getCurrentAuthenticatedUser(authentication); + + List customerOrders = orderService.listOrdersByCustomer(customer); + return customerOrders; } + + //find ordered items by Customer @isAuthenticatedAsAdminOrUser @GetMapping("/findOrderedItemsByCustomer") public List findOrderedItemsByCustomer(@AuthenticationPrincipal Authentication authentication){ - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (!(authentication instanceof AnonymousAuthenticationToken)){ - String currentUserEmail = authentication.getName(); - User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found")); - List customerOrderedItems = orderProductsService.findOrderItemsByCustomer(customer); - return customerOrderedItems; - }else{ - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } + User customer = commonService.getCurrentAuthenticatedUser(authentication); + List customerOrderedItems = orderProductsService.findOrderItemsByCustomer(customer); + return customerOrderedItems; } + + } diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java index d5e2605..b34e2ed 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java +++ b/src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java @@ -77,4 +77,10 @@ public ResponseEntity deleteProduct(@PathVariable Long productId){ return new ResponseEntity<>("Product with id: "+ productId +" is deleted successfully:)", HttpStatus.OK); } + //search product api + @GetMapping("/search") + public List searchProduct(@RequestParam(value = "query") String query){ + return productService.searchProduct(query); + } + } diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/SettingController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/SettingController.java new file mode 100644 index 0000000..053edbd --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/controller/SettingController.java @@ -0,0 +1,41 @@ +package com.manir.springbootecommercerestapi.controller; + +import com.manir.springbootecommercerestapi.dto.SettingDto; +import com.manir.springbootecommercerestapi.model.Setting; +import com.manir.springbootecommercerestapi.repository.SettingRepository; +import com.manir.springbootecommercerestapi.service.SettingService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.Optional; + +@RestController +@RequestMapping(value = "api/v1/setting") +public class SettingController { + @Autowired + private SettingService settingService; + @Autowired + private SettingRepository settingRepository; + + //post first setting api + @PreAuthorize("hasRole('ADMIN')") + @PostMapping("/createSetting") + public ResponseEntity createSetting(@RequestBody SettingDto settingDto){ + SettingDto createdSetting = settingService.addSettingFirstTime(settingDto); + return new ResponseEntity<>(createdSetting, HttpStatus.CREATED); + } + + //edit existing setting api + @PreAuthorize("hasRole('ADMIN')") + @PutMapping("/editSetting") + public ResponseEntity editSetting(@RequestBody SettingDto settingDto){ + Optional existingSetting = settingRepository.findAll().stream().findFirst(); + SettingDto editedSetting = settingService.updateSetting(settingDto, existingSetting.get().getId()); + + return ResponseEntity.ok(editedSetting); + } + +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/controller/ShoppingCartController.java b/src/main/java/com/manir/springbootecommercerestapi/controller/ShoppingCartController.java index 7cac9e1..c3bdfc5 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/controller/ShoppingCartController.java +++ b/src/main/java/com/manir/springbootecommercerestapi/controller/ShoppingCartController.java @@ -1,20 +1,15 @@ package com.manir.springbootecommercerestapi.controller; -import com.manir.springbootecommercerestapi.exception.EcommerceApiException; import com.manir.springbootecommercerestapi.model.User; -import com.manir.springbootecommercerestapi.repository.UserRepository; import com.manir.springbootecommercerestapi.response.CartItemResponse; -import com.manir.springbootecommercerestapi.service.OrderService; +import com.manir.springbootecommercerestapi.service.CommonService; import com.manir.springbootecommercerestapi.service.ShoppingCartService; import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @@ -26,26 +21,16 @@ public class ShoppingCartController { @Resource private ShoppingCartService shoppingCartService; @Autowired - private UserRepository userRepository; - @Autowired - private OrderService orderService; + private CommonService commonService; //find by customer api @isAuthenticatedAsAdminOrUser @GetMapping("/findByCustomer") public CartItemResponse findByCustomerId(@AuthenticationPrincipal Authentication authentication){ - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (!(authentication instanceof AnonymousAuthenticationToken)) { - String currentUserEmail = authentication.getName(); - //System.out.println("Name:" + currentUserEmail); - User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(()-> new UsernameNotFoundException("Customer not found")); - CartItemResponse responseCartItems = shoppingCartService.findByCustomer(customer); - return responseCartItems; - - }else{ - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } + User customer = commonService.getCurrentAuthenticatedUser(authentication); + CartItemResponse responseCartItems = shoppingCartService.findByCustomer(customer); + return responseCartItems; } //add item to the cart api @@ -54,15 +39,10 @@ public CartItemResponse findByCustomerId(@AuthenticationPrincipal Authentication public ResponseEntity addCartItem(@AuthenticationPrincipal Authentication authentication, @PathVariable Long productId, @PathVariable Integer quantity){ - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (!(authentication instanceof AnonymousAuthenticationToken)){ - String currentUserEmail = authentication.getName(); - User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer not found")); - CartItemResponse responseCartItem = shoppingCartService.addCartItem(customer, productId, quantity); - return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED); - }else { - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } + + User customer = commonService.getCurrentAuthenticatedUser(authentication); + CartItemResponse responseCartItem = shoppingCartService.addCartItem(customer, productId, quantity); + return new ResponseEntity<>(responseCartItem, HttpStatus.CREATED); } //update item quantity api @@ -71,15 +51,9 @@ public ResponseEntity addCartItem(@AuthenticationPrincipal Aut public ResponseEntity updateItemQuantity(@AuthenticationPrincipal Authentication authentication, @PathVariable Long productId, @PathVariable Integer quantity){ - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (!(authentication instanceof AnonymousAuthenticationToken)){ - String currentUserEmail = authentication.getName(); - User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found")); - CartItemResponse responseCartItem = shoppingCartService.updateItemQuantity(customer, productId, quantity); - return new ResponseEntity<>(responseCartItem, HttpStatus.OK); - }else{ - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } + User customer = commonService.getCurrentAuthenticatedUser(authentication); + CartItemResponse responseCartItem = shoppingCartService.updateItemQuantity(customer, productId, quantity); + return new ResponseEntity<>(responseCartItem, HttpStatus.OK); } //delete item product api @@ -87,15 +61,10 @@ public ResponseEntity updateItemQuantity(@AuthenticationPrinci @DeleteMapping("/deleteItemProduct/{productId}") public ResponseEntity deleteItemProduct(@AuthenticationPrincipal Authentication authentication, @PathVariable Long productId){ - authentication = SecurityContextHolder.getContext().getAuthentication(); - if (!(authentication instanceof AnonymousAuthenticationToken)){ - String currentUserEmail = authentication.getName(); - User customer = userRepository.findByEmail(currentUserEmail).orElseThrow(() -> new UsernameNotFoundException("Customer Not found")); - shoppingCartService.deleteItemProduct(customer, productId); - return ResponseEntity.ok("Product with id = " + productId +" is deleted successfully from your shopping cart"); - }else{ - throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); - } + + User customer = commonService.getCurrentAuthenticatedUser(authentication); + shoppingCartService.deleteItemProduct(customer, productId); + return ResponseEntity.ok("Product with id = " + productId +" is deleted successfully from your shopping cart"); } diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/ContactDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/ContactDto.java new file mode 100644 index 0000000..338891d --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/dto/ContactDto.java @@ -0,0 +1,15 @@ +package com.manir.springbootecommercerestapi.dto; + +import lombok.Data; + +@Data +public class ContactDto { + private Long id; + private String name; + private String email; + private String phone; + private String subject; + private String message; + private String ipAddress; + private String status; +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/FaqDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/FaqDto.java new file mode 100644 index 0000000..a476603 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/dto/FaqDto.java @@ -0,0 +1,12 @@ +package com.manir.springbootecommercerestapi.dto; + +import com.manir.springbootecommercerestapi.model.BaseEntity; +import lombok.Data; + +@Data +public class FaqDto extends BaseEntity { + private Long id; + private String question; + private String answer; + private String status; +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/ProfileDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/ProfileDto.java new file mode 100644 index 0000000..ae0c350 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/dto/ProfileDto.java @@ -0,0 +1,11 @@ +package com.manir.springbootecommercerestapi.dto; + +import lombok.Data; + +@Data +public class ProfileDto { + private Long id; + private String image; + private String address; + private String phone; +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/dto/SettingDto.java b/src/main/java/com/manir/springbootecommercerestapi/dto/SettingDto.java new file mode 100644 index 0000000..676cbc7 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/dto/SettingDto.java @@ -0,0 +1,27 @@ +package com.manir.springbootecommercerestapi.dto; + +import lombok.Data; + +@Data +public class SettingDto { + private Long id; + private String title; + private String keywords; + private String description; + private String company; + private String address; + private String phone; + private String fax; + private String email; + private String smtpServer; + private String smtpEmail; + private String smtpPassword; + private Integer smtpPort; + private String facebook; + private String instagram; + private String twitter; + private String aboutUs; + private String contact; + private String reference; + private String status; +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/BaseEntity.java b/src/main/java/com/manir/springbootecommercerestapi/model/BaseEntity.java new file mode 100644 index 0000000..e9e620f --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/model/BaseEntity.java @@ -0,0 +1,38 @@ +package com.manir.springbootecommercerestapi.model; + +import lombok.Data; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.Column; +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import java.time.LocalDateTime; + +@Data +@MappedSuperclass +/** + Auditing allows us : to see who created data and who updated + then we should enable jpa auditing... + **/ +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseEntity { + + @CreatedDate + @Column(name = "created_at", updatable = false) + private LocalDateTime createdAt; + @CreatedBy + @Column(updatable = false) + private String createdBy; + + @LastModifiedDate + @Column(name = "updated_at", insertable = false) + private LocalDateTime updatedAt; + @LastModifiedBy + @Column(insertable = false) + private String updatedBy; + +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java b/src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java index 70155da..5a1c4ea 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java @@ -11,7 +11,7 @@ @Data @Entity @Table(name = "cart_item") -public class CartItem { +public class CartItem extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Category.java b/src/main/java/com/manir/springbootecommercerestapi/model/Category.java index 6d4e01c..3862154 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Category.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Category.java @@ -14,7 +14,7 @@ @Entity @Table(name = "categories") @JsonIgnoreProperties(value = {"children"}) -public class Category { +public class Category extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Comment.java b/src/main/java/com/manir/springbootecommercerestapi/model/Comment.java index 986eaa7..cd69ca0 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Comment.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Comment.java @@ -9,7 +9,7 @@ @Getter @Entity @Table(name = "product_comments") -public class Comment { +public class Comment extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -23,4 +23,9 @@ public class Comment { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "product_id") private Product product; + + //relation with user + @ManyToOne() + @JoinColumn(name = "customer_id") + private User customer; } diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Contact.java b/src/main/java/com/manir/springbootecommercerestapi/model/Contact.java new file mode 100644 index 0000000..e321566 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Contact.java @@ -0,0 +1,26 @@ +package com.manir.springbootecommercerestapi.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@AllArgsConstructor +@NoArgsConstructor +@Data +@Entity +@Table(name = "contact") +public class Contact extends BaseEntity{ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String name; + private String email; + private String phone; + private String subject; + private String message; + private String ipAddress; + private String status; + +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Faq.java b/src/main/java/com/manir/springbootecommercerestapi/model/Faq.java new file mode 100644 index 0000000..369f411 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Faq.java @@ -0,0 +1,22 @@ +package com.manir.springbootecommercerestapi.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@AllArgsConstructor +@NoArgsConstructor +@Data +@Entity +@Table(name = "faqs") +public class Faq extends BaseEntity{ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String question; + private String answer; + private String status; + +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java b/src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java index 2a76534..45b3d3d 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java @@ -10,7 +10,7 @@ @NoArgsConstructor @Entity @Table(name = "product_image_gallery") -public class ImageData { +public class ImageData extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Order.java b/src/main/java/com/manir/springbootecommercerestapi/model/Order.java index 73e9f68..189875c 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Order.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Order.java @@ -11,7 +11,7 @@ @Setter @Entity @Table(name = "orders") -public class Order { +public class Order extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java b/src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java index b9362c5..084ea70 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java @@ -11,7 +11,7 @@ @Data @Entity @Table(name = "order_products") -public class OrderProducts { +public class OrderProducts extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Product.java b/src/main/java/com/manir/springbootecommercerestapi/model/Product.java index 78c7f3b..1333432 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Product.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Product.java @@ -12,7 +12,7 @@ @Setter @Entity @Table(name = "products") -public class Product { +public class Product extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Profile.java b/src/main/java/com/manir/springbootecommercerestapi/model/Profile.java new file mode 100644 index 0000000..da592e4 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Profile.java @@ -0,0 +1,27 @@ +package com.manir.springbootecommercerestapi.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@AllArgsConstructor +@NoArgsConstructor +@Data +@Entity +@Table(name = "user_profile") +public class Profile extends BaseEntity{ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String image; + private String address; + private String phone; + + //relation with user + @OneToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "user_id", referencedColumnName = "id") + private User user; + +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Role.java b/src/main/java/com/manir/springbootecommercerestapi/model/Role.java index 3ad1a0e..4f792f4 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/Role.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Role.java @@ -7,7 +7,7 @@ @Data @Entity @Table(name = "roles") -public class Role { +public class Role extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/Setting.java b/src/main/java/com/manir/springbootecommercerestapi/model/Setting.java new file mode 100644 index 0000000..ea839f9 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/model/Setting.java @@ -0,0 +1,38 @@ +package com.manir.springbootecommercerestapi.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@AllArgsConstructor +@NoArgsConstructor +@Data +@Entity +@Table(name = "settings") +public class Setting extends BaseEntity{ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String title; + private String keywords; + private String description; + private String company; + private String address; + private String phone; + private String fax; + private String email; + private String smtpServer; + private String smtpEmail; + private String smtpPassword; + private Integer smtpPort; + private String facebook; + private String instagram; + private String twitter; + private String aboutUs; + private String contact; + private String reference; + private String status; + +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/model/User.java b/src/main/java/com/manir/springbootecommercerestapi/model/User.java index edc66b9..5ca2a50 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/model/User.java +++ b/src/main/java/com/manir/springbootecommercerestapi/model/User.java @@ -13,7 +13,7 @@ @Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = {"userName"}), @UniqueConstraint(columnNames = {"email"}) }) -public class User { +public class User extends BaseEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -46,4 +46,14 @@ public class User { fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "customer") private Set orderProducts; + + //relation with comment or review + @OneToMany(cascade = CascadeType.ALL, + fetch = FetchType.LAZY, orphanRemoval = true, + mappedBy = "customer") + private Set comments; + + //relation with profile + @OneToOne(mappedBy = "user") + private Profile user_profile; } diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/CommentRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/CommentRepository.java index 74fb923..8fa17c5 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/CommentRepository.java +++ b/src/main/java/com/manir/springbootecommercerestapi/repository/CommentRepository.java @@ -1,10 +1,12 @@ package com.manir.springbootecommercerestapi.repository; import com.manir.springbootecommercerestapi.model.Comment; +import com.manir.springbootecommercerestapi.model.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CommentRepository extends JpaRepository { List findByProductId(Long productId); + List findByCustomer(User customer); } diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/ContactRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/ContactRepository.java new file mode 100644 index 0000000..3e2911a --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/repository/ContactRepository.java @@ -0,0 +1,7 @@ +package com.manir.springbootecommercerestapi.repository; + +import com.manir.springbootecommercerestapi.model.Contact; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ContactRepository extends JpaRepository { +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/FaqRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/FaqRepository.java new file mode 100644 index 0000000..3fc9ed1 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/repository/FaqRepository.java @@ -0,0 +1,7 @@ +package com.manir.springbootecommercerestapi.repository; + +import com.manir.springbootecommercerestapi.model.Faq; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FaqRepository extends JpaRepository { +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/ProductRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/ProductRepository.java index 2e29f5b..419dd56 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/repository/ProductRepository.java +++ b/src/main/java/com/manir/springbootecommercerestapi/repository/ProductRepository.java @@ -2,7 +2,19 @@ import com.manir.springbootecommercerestapi.model.Product; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; public interface ProductRepository extends JpaRepository { + @Query( + "SELECT p FROM Product p WHERE " + + "p.title LIKE CONCAT('%', :query, '%') " + + "or p.description LIKE CONCAT('%', :query, '%')" + + "or p.keywords LIKE CONCAT('%', :query, '%')" + + "or p.detail LIKE CONCAT('%', :query, '%')" + ) + List searchProduct(String query); + } diff --git a/src/main/java/com/manir/springbootecommercerestapi/repository/SettingRepository.java b/src/main/java/com/manir/springbootecommercerestapi/repository/SettingRepository.java new file mode 100644 index 0000000..94b6cb4 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/repository/SettingRepository.java @@ -0,0 +1,7 @@ +package com.manir.springbootecommercerestapi.repository; + +import com.manir.springbootecommercerestapi.model.Setting; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SettingRepository extends JpaRepository { +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java b/src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java index 1741fed..575ad74 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java @@ -2,13 +2,15 @@ import com.manir.springbootecommercerestapi.dto.CommentDto; +import com.manir.springbootecommercerestapi.model.User; import java.util.List; public interface CommentService { - CommentDto createComment(Long productId, CommentDto commentDto); + CommentDto createComment(User customer, Long productId, CommentDto commentDto); + List findCommentByCustomer(User customer); List getAllComments(); List getAllCommentsByProductId(Long productId); CommentDto getCommentById(Long productId, Long commentId); diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java b/src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java index 1dfce02..f973fb0 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/CommonService.java @@ -1,9 +1,11 @@ package com.manir.springbootecommercerestapi.service; import com.manir.springbootecommercerestapi.dto.CartItemDto; +import com.manir.springbootecommercerestapi.model.User; import com.manir.springbootecommercerestapi.response.CartItemResponse; import com.manir.springbootecommercerestapi.response.CommonResponse; import org.springframework.data.domain.Page; +import org.springframework.security.core.Authentication; import java.util.List; @@ -14,4 +16,13 @@ public interface CommonService { //cart iem response handler CartItemResponse getResponse(CartItemDto cartItemDto); + + //get current authenticated user + User getCurrentAuthenticatedUser(Authentication authentication); + + //entity mapper + T mapToEntity(T type); + + //dto mapper + T mapToDto(T type); } diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/ContactService.java b/src/main/java/com/manir/springbootecommercerestapi/service/ContactService.java new file mode 100644 index 0000000..65223b0 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/ContactService.java @@ -0,0 +1,11 @@ +package com.manir.springbootecommercerestapi.service; + +import com.manir.springbootecommercerestapi.dto.ContactDto; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +public interface ContactService { + ContactDto sendMessage(ContactDto contactDto, HttpServletRequest request); + List getMessages(); +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/FaqService.java b/src/main/java/com/manir/springbootecommercerestapi/service/FaqService.java new file mode 100644 index 0000000..acfe24e --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/FaqService.java @@ -0,0 +1,13 @@ +package com.manir.springbootecommercerestapi.service; + +import com.manir.springbootecommercerestapi.dto.FaqDto; + +import java.util.List; + +public interface FaqService { + FaqDto addFaq(FaqDto faqDto); + List listAllFaqs(); + FaqDto getFaqById(Long id); + FaqDto updateFaq(FaqDto faqDto, Long id); + void deleteFaq(Long id); +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java index fcbb875..f3ade8d 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java @@ -3,10 +3,12 @@ import com.manir.springbootecommercerestapi.dto.CommentDto; import com.manir.springbootecommercerestapi.exception.EcommerceApiException; import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; +import com.manir.springbootecommercerestapi.model.User; import com.manir.springbootecommercerestapi.repository.CommentRepository; import com.manir.springbootecommercerestapi.repository.ProductRepository; import com.manir.springbootecommercerestapi.model.Comment; import com.manir.springbootecommercerestapi.model.Product; +import com.manir.springbootecommercerestapi.repository.UserRepository; import com.manir.springbootecommercerestapi.service.CommentService; import org.modelmapper.ModelMapper; import org.springframework.http.HttpStatus; @@ -25,15 +27,18 @@ public class CommentServiceImpl implements CommentService { private CommentRepository commentRepository; @Resource private ProductRepository productRepository; + @Resource + private UserRepository userRepository; @Override - public CommentDto createComment(Long productId, CommentDto commentDto) { - + public CommentDto createComment(User customer, Long productId, CommentDto commentDto) { + User user = findCustomerById(customer.getId()); Product product = findProductById(productId); //convert to entity Comment comment = mapToEntity(commentDto); //save to db comment.setProduct(product); + comment.setCustomer(user); Comment createdComment = commentRepository.save(comment); //convert to dto CommentDto responseComment = mapToDto(createdComment); @@ -41,6 +46,18 @@ public CommentDto createComment(Long productId, CommentDto commentDto) { return responseComment; } + @Override + public List findCommentByCustomer(User customer) { + List comments = commentRepository.findByCustomer(customer); + if (comments.size() == 0){ + throw new EcommerceApiException("User has no comment or review", HttpStatus.BAD_REQUEST); + } + List commentDtoList = comments.stream() + .map(comment -> mapToDto(comment)) + .collect(Collectors.toList()); + return commentDtoList; + } + @Override public List getAllComments() { List comments = commentRepository.findAll(); @@ -120,4 +137,8 @@ private Comment findCommentById(Long commentId){ return comment; } + private User findCustomerById(Long customerId){ + User customer = userRepository.findById(customerId).orElseThrow(()->new ResourceNotFoundException("Customer", customerId)); + return customer; + } } diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommonServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommonServiceImpl.java index de3fec7..bc633ab 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommonServiceImpl.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommonServiceImpl.java @@ -1,24 +1,44 @@ package com.manir.springbootecommercerestapi.service.Impl; import com.manir.springbootecommercerestapi.dto.CartItemDto; +import com.manir.springbootecommercerestapi.exception.EcommerceApiException; +import com.manir.springbootecommercerestapi.model.User; +import com.manir.springbootecommercerestapi.repository.UserRepository; import com.manir.springbootecommercerestapi.response.CartItemResponse; import com.manir.springbootecommercerestapi.response.CommonResponse; import com.manir.springbootecommercerestapi.service.CommonService; +import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; + +import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Service @Slf4j +@AllArgsConstructor +@Component("commonService") public class CommonServiceImpl implements CommonService{ private static Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class); + @Resource(name = "userRepository") + private final UserRepository userRepository; + @Resource(name = "modelMapper") + private final ModelMapper modelMapper; + @Override public CommonResponse getResponseContent(Page page, List dtoList) { @@ -45,4 +65,31 @@ public CartItemResponse getResponse(CartItemDto cartItemDto) { cartItemResponse.setTotalCost(totalPrice); return cartItemResponse; } + + @Override + public User getCurrentAuthenticatedUser(Authentication authentication) { + authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication == null || authentication instanceof AnonymousAuthenticationToken){ + throw new EcommerceApiException("User not authenticated", HttpStatus.BAD_REQUEST); + } + String currentUserEmail = authentication.getName(); + User currentUser = userRepository.findByEmail(currentUserEmail) + .orElseThrow( + () -> new UsernameNotFoundException("User Not found") + ); + + return currentUser; + } + + @Override + public Object mapToEntity(Object type) { + Object entityObject = modelMapper.map(type, Object.class); + return entityObject; + } + + @Override + public Object mapToDto(Object type) { + Object dtoObject = modelMapper.map(type, Object.class); + return dtoObject; + } } diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ContactServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ContactServiceImpl.java new file mode 100644 index 0000000..db39d0a --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ContactServiceImpl.java @@ -0,0 +1,57 @@ +package com.manir.springbootecommercerestapi.service.Impl; + +import com.manir.springbootecommercerestapi.dto.ContactDto; +import com.manir.springbootecommercerestapi.model.Contact; +import com.manir.springbootecommercerestapi.repository.ContactRepository; +import com.manir.springbootecommercerestapi.service.ContactService; +import com.manir.springbootecommercerestapi.utils.RequestClientIP; +import lombok.AllArgsConstructor; +import org.modelmapper.ModelMapper; +import org.springframework.stereotype.Service; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@AllArgsConstructor +public class ContactServiceImpl implements ContactService { + + @Resource(name = "contactRepository") + private final ContactRepository contactRepository; + @Resource(name = "modelMapper") + private final ModelMapper modelMapper; + @Override + public ContactDto sendMessage(ContactDto contactDto, HttpServletRequest request) { + + Contact contact = mapToEntity(contactDto); + String ipAddress = RequestClientIP.getClientIpAddress(request); + contact.setIpAddress(ipAddress); + Contact createdMessage = contactRepository.save(contact); + + return mapToDto(createdMessage); + } + + @Override + public List getMessages() { + List messages = contactRepository.findAll(); + + return messages.stream() + .map(message -> mapToDto(message)) + .collect(Collectors.toList()); + } + + //map to entity + private Contact mapToEntity(ContactDto contactDto){ + Contact contact = modelMapper.map(contactDto, Contact.class); + return contact; + } + //map to dto + private ContactDto mapToDto(Contact contact){ + ContactDto contactDto = modelMapper.map(contact, ContactDto.class); + return contactDto; + } +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/FaqServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/FaqServiceImpl.java new file mode 100644 index 0000000..1732722 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/FaqServiceImpl.java @@ -0,0 +1,72 @@ +package com.manir.springbootecommercerestapi.service.Impl; + +import com.manir.springbootecommercerestapi.dto.FaqDto; +import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; +import com.manir.springbootecommercerestapi.model.Faq; +import com.manir.springbootecommercerestapi.repository.FaqRepository; +import com.manir.springbootecommercerestapi.service.CommonService; +import com.manir.springbootecommercerestapi.service.FaqService; +import com.manir.springbootecommercerestapi.service.MapperService; +import lombok.AllArgsConstructor; +import org.modelmapper.ModelMapper; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; +import java.util.stream.Collectors; + +@Service +@AllArgsConstructor +public class FaqServiceImpl implements FaqService { + @Resource(name = "faqRepository") + private final FaqRepository faqRepository; + @Resource(name = "modelMapper") + private final ModelMapper modelMapper; + @Resource(name = "mapperService") + private final MapperService mapperService; + + @Override + public FaqDto addFaq(FaqDto faqDto) { + Faq faq = mapperService.mapToEntity(faqDto); + Faq addedFaq = faqRepository.save(faq); + + return mapperService.mapToDto(addedFaq); + } + + @Override + public List listAllFaqs() { + List faqs = faqRepository.findAll(); + return faqs.stream().map(faq -> mapperService.mapToDto(faq)).collect(Collectors.toList()); + } + + @Override + public FaqDto getFaqById(Long id) { + Faq faq = faqRepository.findById(id).orElseThrow(()->new ResourceNotFoundException("Faq", id)); + return mapToDto(faq); + } + + @Override + public FaqDto updateFaq(FaqDto faqDto, Long id) { + Faq faq = faqRepository.findById(id).orElseThrow(()->new ResourceNotFoundException("Faq", id)); + faq.setQuestion(faqDto.getQuestion()); + faq.setAnswer(faqDto.getAnswer()); + Faq updatedFaq = faqRepository.save(faq); + return mapToDto(updatedFaq); + } + + @Override + public void deleteFaq(Long id) { + Faq faq = faqRepository.findById(id).orElseThrow(()->new ResourceNotFoundException("Faq", id)); + faqRepository.delete(faq); + } + + private FaqDto mapToDto(Faq faq){ + FaqDto faqDto = modelMapper.map(faq, FaqDto.class); + return faqDto; + } + //map to entity + private Faq mapToEntity(FaqDto faqDto){ + Faq faq = modelMapper.map(faqDto, Faq.class); + return faq; + } +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java index 8b58f61..72a6138 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java @@ -41,12 +41,10 @@ public class OrderServiceImpl implements OrderService { @Transactional public void placeOrder(User customer) { CartItemResponse cartItemDto = shoppingCartService.findByCustomer(customer); - OrderDto orderDto = new OrderDto(); - orderDto.setTotalPrice(cartItemDto.getTotalCost()); - orderDto.setEmail(customer.getEmail()); - orderDto.setName(customer.getName()); - orderDto.setCustomer(customer); - OrderDto savedOrder = saveOrder(orderDto, customer); + //set order fields + OrderDto orderDto = setFields(cartItemDto, customer); + //save order to the db + OrderDto savedOrder = saveOrder(orderDto); List cartItemDtoList = cartItemDto.getContent(); for(CartItemDto cartItem : cartItemDtoList){ OrderProducts orderProducts = new OrderProducts(); @@ -62,7 +60,7 @@ public void placeOrder(User customer) { } @Override - public OrderDto saveOrder(OrderDto orderDto, User customer) { + public OrderDto saveOrder(OrderDto orderDto) { //convert to entity Order order = mapToEntity(orderDto); //save order to db @@ -70,6 +68,15 @@ public OrderDto saveOrder(OrderDto orderDto, User customer) { return mapToDto(placedOrder); } + private OrderDto setFields(CartItemResponse cartItemDto, User customer){ + OrderDto orderDto = new OrderDto(); + orderDto.setTotalPrice(cartItemDto.getTotalCost()); + orderDto.setEmail(customer.getEmail()); + orderDto.setName(customer.getName()); + orderDto.setCustomer(customer); + + return orderDto; + } @Override public List listOrdersByCustomer(User customer) { List orders = orderRepository.findByCustomer(customer); diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductServiceImpl.java index 2f4fd98..9b3dcb6 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductServiceImpl.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/ProductServiceImpl.java @@ -1,6 +1,7 @@ package com.manir.springbootecommercerestapi.service.Impl; import com.manir.springbootecommercerestapi.dto.ProductDto; +import com.manir.springbootecommercerestapi.exception.EcommerceApiException; import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; import com.manir.springbootecommercerestapi.repository.CategoryRepository; import com.manir.springbootecommercerestapi.repository.ProductRepository; @@ -17,6 +18,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; @@ -131,6 +133,18 @@ public ProductDto saveProductByCategoryId(Long categoryId, ProductDto productDto return responseProduct; } + @Override + public List searchProduct(String query) { + List products = productRepository.searchProduct(query); + if (products.size() == 0){ + throw new EcommerceApiException("No product is found", HttpStatus.BAD_REQUEST); + } + List productDtoList = products.stream() + .map(product -> mapToDto(product)) + .collect(Collectors.toList()); + return productDtoList; + } + //upload image private String uploadProductImage(MultipartFile file){ ProductDto productDto = new ProductDto(); diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/Impl/SettingServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/SettingServiceImpl.java new file mode 100644 index 0000000..b697560 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/Impl/SettingServiceImpl.java @@ -0,0 +1,75 @@ +package com.manir.springbootecommercerestapi.service.Impl; + +import com.manir.springbootecommercerestapi.dto.SettingDto; +import com.manir.springbootecommercerestapi.exception.EcommerceApiException; +import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException; +import com.manir.springbootecommercerestapi.model.Setting; +import com.manir.springbootecommercerestapi.repository.SettingRepository; +import com.manir.springbootecommercerestapi.service.SettingService; +import lombok.AllArgsConstructor; +import org.modelmapper.ModelMapper; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Optional; + +@Service +@AllArgsConstructor +public class SettingServiceImpl implements SettingService { + @Resource(name = "settingRepository") + private final SettingRepository settingRepository; + @Resource(name = "modelMapper") + private final ModelMapper modelMapper; + + @Override + public SettingDto addSettingFirstTime(SettingDto settingDto) { + + Optional setting = settingRepository.findAll().stream().findFirst(); + if (!setting.isPresent()){ + Setting firstSetting = mapToEntity(settingDto); + Setting saveSetting = settingRepository.save(firstSetting); + return mapToDto(saveSetting); + }else { + throw new EcommerceApiException("Setting already exists, please edit it only", HttpStatus.BAD_REQUEST); + } + } + + @Override + public SettingDto updateSetting(SettingDto settingDto, Long id) { + Setting setting = settingRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Setting", id)); + setting.setTitle(settingDto.getTitle()); + setting.setKeywords(settingDto.getKeywords()); + setting.setDescription(settingDto.getDescription()); + setting.setCompany(settingDto.getCompany()); + setting.setAddress(settingDto.getAddress()); + setting.setPhone(settingDto.getPhone()); + setting.setFax(settingDto.getFax()); + setting.setEmail(settingDto.getEmail()); + setting.setSmtpServer(settingDto.getSmtpServer()); + setting.setSmtpEmail(settingDto.getSmtpEmail()); + setting.setSmtpPassword(settingDto.getSmtpPassword()); + setting.setSmtpPort(settingDto.getSmtpPort()); + setting.setFacebook(settingDto.getFacebook()); + setting.setInstagram(settingDto.getInstagram()); + setting.setTwitter(settingDto.getTwitter()); + setting.setAboutUs(settingDto.getAboutUs()); + setting.setContact(settingDto.getContact()); + setting.setContact(settingDto.getReference()); + //save setting changes + Setting editedSetting = settingRepository.save(setting); + + return mapToDto(editedSetting); + } + + //map to dto + private SettingDto mapToDto(Setting setting){ + SettingDto settingDto = modelMapper.map(setting, SettingDto.class); + return settingDto; + } + //map to entity + private Setting mapToEntity(SettingDto settingDto){ + Setting setting = modelMapper.map(settingDto, Setting.class); + return setting; + } +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/MapperService.java b/src/main/java/com/manir/springbootecommercerestapi/service/MapperService.java new file mode 100644 index 0000000..33a4150 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/MapperService.java @@ -0,0 +1,9 @@ +package com.manir.springbootecommercerestapi.service; + +public interface MapperService{ + //entity mapper + E mapToEntity(D type); + + //dto mapper + D mapToDto(E type); +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/MapperServiceImpl.java b/src/main/java/com/manir/springbootecommercerestapi/service/MapperServiceImpl.java new file mode 100644 index 0000000..9857292 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/MapperServiceImpl.java @@ -0,0 +1,40 @@ +package com.manir.springbootecommercerestapi.service; + + +import lombok.Data; +import org.modelmapper.ModelMapper; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + + +@Service +@Component("mapperService") +@Data +public class MapperServiceImpl implements MapperService { + + + @Resource(name = "modelMapper") + private final ModelMapper modelMapper; + + private Class entityClass; + + private Class dtoClass; + + public MapperServiceImpl(ModelMapper modelMapper) { + this.modelMapper = modelMapper; + } + + @Override + public E mapToEntity(D type) { + E model = modelMapper.map(type, getEntityClass()); + return model; + } + + @Override + public D mapToDto(E type) { + D dto = modelMapper.map(type, getDtoClass()); + return dto; + } +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java b/src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java index e2d9da9..2ff968d 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/OrderService.java @@ -8,6 +8,6 @@ public interface OrderService { void placeOrder(User customer); - OrderDto saveOrder(OrderDto orderDto, User customer); + OrderDto saveOrder(OrderDto orderDto); List listOrdersByCustomer(User customer); } diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/ProductService.java b/src/main/java/com/manir/springbootecommercerestapi/service/ProductService.java index 9853f05..803e650 100644 --- a/src/main/java/com/manir/springbootecommercerestapi/service/ProductService.java +++ b/src/main/java/com/manir/springbootecommercerestapi/service/ProductService.java @@ -15,4 +15,6 @@ public interface ProductService { void deleteProduct(Long productId); ProductDto saveProductByCategoryId(Long categoryId, ProductDto productDto); + + List searchProduct(String query); } diff --git a/src/main/java/com/manir/springbootecommercerestapi/service/SettingService.java b/src/main/java/com/manir/springbootecommercerestapi/service/SettingService.java new file mode 100644 index 0000000..05c010e --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/service/SettingService.java @@ -0,0 +1,8 @@ +package com.manir.springbootecommercerestapi.service; + +import com.manir.springbootecommercerestapi.dto.SettingDto; + +public interface SettingService { + SettingDto addSettingFirstTime(SettingDto settingDto); + SettingDto updateSetting(SettingDto settingDto, Long id); +} diff --git a/src/main/java/com/manir/springbootecommercerestapi/utils/RequestClientIP.java b/src/main/java/com/manir/springbootecommercerestapi/utils/RequestClientIP.java new file mode 100644 index 0000000..5920839 --- /dev/null +++ b/src/main/java/com/manir/springbootecommercerestapi/utils/RequestClientIP.java @@ -0,0 +1,41 @@ +package com.manir.springbootecommercerestapi.utils; + +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +public class RequestClientIP { + + private static final String[] IP_HEADER_CANDIDATES = { + "X-Forwarded-For", + "Proxy-Client-IP", + "WL-Proxy-Client-IP", + "HTTP_X_FORWARDED_FOR", + "HTTP_X_FORWARDED", + "HTTP_X_CLUSTER_CLIENT_IP", + "HTTP_CLIENT_IP", + "HTTP_FORWARDED_FOR", + "HTTP_FORWARDED", + "HTTP_VIA", + "REMOTE_ADDR" + }; + + public static String getClientIpAddress(HttpServletRequest request) { + + if (RequestContextHolder.getRequestAttributes() == null) { + return "0.0.0.0"; + } + + request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + for (String header: IP_HEADER_CANDIDATES) { + String ipList = request.getHeader(header); + if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) { + String ip = ipList.split(",")[0]; + return ip; + } + } + + return request.getRemoteAddr(); + } +}