Skip to content

Commit 4ebd51f

Browse files
committed
Auditing and Comment code refactors.
1 parent fe37854 commit 4ebd51f

17 files changed

+128
-15
lines changed

src/main/java/com/manir/springbootecommercerestapi/SpringBootECommerceRestApiApplication.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
import org.springframework.boot.SpringApplication;
55
import org.springframework.boot.autoconfigure.SpringBootApplication;
66
import org.springframework.context.annotation.Bean;
7+
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
78

89
@SpringBootApplication
10+
@EnableJpaAuditing(auditorAwareRef = "auditAwareImpl")
911
public class SpringBootECommerceRestApiApplication {
1012

1113
public static void main(String[] args) {
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.manir.springbootecommercerestapi.audit;
2+
3+
import org.springframework.data.domain.AuditorAware;
4+
import org.springframework.security.core.context.SecurityContextHolder;
5+
import org.springframework.stereotype.Component;
6+
7+
import java.util.Optional;
8+
9+
@Component("auditAwareImpl")
10+
public class AuditAwareImpl implements AuditorAware<String> {
11+
@Override
12+
public Optional<String> getCurrentAuditor() {
13+
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName());
14+
}
15+
}

src/main/java/com/manir/springbootecommercerestapi/controller/CommentController.java

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
package com.manir.springbootecommercerestapi.controller;
22

33
import com.manir.springbootecommercerestapi.dto.CommentDto;
4+
import com.manir.springbootecommercerestapi.model.User;
45
import com.manir.springbootecommercerestapi.service.CommentService;
6+
import com.manir.springbootecommercerestapi.service.CommonService;
7+
import com.manir.springbootecommercerestapi.utils.isAuthenticatedAsAdminOrUser;
8+
import org.springframework.beans.factory.annotation.Autowired;
59
import org.springframework.http.HttpStatus;
610
import org.springframework.http.ResponseEntity;
11+
import org.springframework.security.core.Authentication;
12+
import org.springframework.security.core.annotation.AuthenticationPrincipal;
713
import org.springframework.web.bind.annotation.*;
814

915
import javax.annotation.Resource;
@@ -13,17 +19,30 @@
1319
@RequestMapping(value = "api/v1/products")
1420
public class CommentController {
1521

16-
@Resource
22+
@Autowired
1723
private CommentService commentService;
24+
@Autowired
25+
private CommonService commonService;
1826

1927
//create comment api
28+
@isAuthenticatedAsAdminOrUser
2029
@PostMapping("/{productId}/createComment")
21-
public ResponseEntity<CommentDto> createComment(@PathVariable Long productId,
30+
public ResponseEntity<CommentDto> createComment(@AuthenticationPrincipal Authentication authentication,
31+
@PathVariable Long productId,
2232
@RequestBody CommentDto commentDto){
23-
CommentDto responseComment = commentService.createComment(productId, commentDto);
33+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
34+
CommentDto responseComment = commentService.createComment(customer, productId, commentDto);
2435
return new ResponseEntity<>(responseComment, HttpStatus.CREATED);
2536
}
2637

38+
//get comment by user
39+
@isAuthenticatedAsAdminOrUser
40+
@GetMapping("/comment/findByUser")
41+
public List<CommentDto> findByUser(@AuthenticationPrincipal Authentication authentication){
42+
User customer = commonService.getCurrentAuthenticatedUser(authentication);
43+
return commentService.findCommentByCustomer(customer);
44+
}
45+
2746
//get all comments api
2847
@GetMapping("/getAllComments")
2948
public List<CommentDto> getAllComments(){
@@ -58,4 +77,6 @@ public ResponseEntity<String> deleteComment(@PathVariable Long productId, @PathV
5877
commentService.deleteComment(productId, commentId);
5978
return ResponseEntity.ok("Comment with id: "+commentId+" is successfully:)");
6079
}
80+
81+
6182
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.manir.springbootecommercerestapi.model;
2+
3+
import lombok.Data;
4+
import org.springframework.data.annotation.CreatedBy;
5+
import org.springframework.data.annotation.CreatedDate;
6+
import org.springframework.data.annotation.LastModifiedBy;
7+
import org.springframework.data.annotation.LastModifiedDate;
8+
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
9+
10+
import javax.persistence.Column;
11+
import javax.persistence.EntityListeners;
12+
import javax.persistence.MappedSuperclass;
13+
import java.time.LocalDateTime;
14+
15+
@Data
16+
@MappedSuperclass
17+
/**
18+
Auditing allows us : to see who created data and who updated
19+
then we should enable jpa auditing...
20+
**/
21+
@EntityListeners(AuditingEntityListener.class)
22+
public abstract class BaseEntity {
23+
24+
@CreatedDate
25+
@Column(name = "created_at", updatable = false)
26+
private LocalDateTime createdAt;
27+
@CreatedBy
28+
@Column(updatable = false)
29+
private String createdBy;
30+
31+
@LastModifiedDate
32+
@Column(name = "updated_at", insertable = false)
33+
private LocalDateTime updatedAt;
34+
@LastModifiedBy
35+
@Column(insertable = false)
36+
private String updatedBy;
37+
38+
}

src/main/java/com/manir/springbootecommercerestapi/model/CartItem.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
@Data
1212
@Entity
1313
@Table(name = "cart_item")
14-
public class CartItem {
14+
public class CartItem extends BaseEntity{
1515
@Id
1616
@GeneratedValue(strategy = GenerationType.IDENTITY)
1717
private Long id;

src/main/java/com/manir/springbootecommercerestapi/model/Category.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
@Entity
1515
@Table(name = "categories")
1616
@JsonIgnoreProperties(value = {"children"})
17-
public class Category {
17+
public class Category extends BaseEntity{
1818

1919
@Id
2020
@GeneratedValue(strategy = GenerationType.IDENTITY)

src/main/java/com/manir/springbootecommercerestapi/model/Comment.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
@Getter
1010
@Entity
1111
@Table(name = "product_comments")
12-
public class Comment {
12+
public class Comment extends BaseEntity{
1313
@Id
1414
@GeneratedValue(strategy = GenerationType.IDENTITY)
1515
private Long id;
@@ -23,4 +23,9 @@ public class Comment {
2323
@ManyToOne(fetch = FetchType.LAZY)
2424
@JoinColumn(name = "product_id")
2525
private Product product;
26+
27+
//relation with user
28+
@ManyToOne()
29+
@JoinColumn(name = "customer_id")
30+
private User customer;
2631
}

src/main/java/com/manir/springbootecommercerestapi/model/ImageData.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
@NoArgsConstructor
1111
@Entity
1212
@Table(name = "product_image_gallery")
13-
public class ImageData {
13+
public class ImageData extends BaseEntity{
1414
@Id
1515
@GeneratedValue(strategy = GenerationType.IDENTITY)
1616
private Long id;

src/main/java/com/manir/springbootecommercerestapi/model/Order.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
@Setter
1212
@Entity
1313
@Table(name = "orders")
14-
public class Order {
14+
public class Order extends BaseEntity{
1515
@Id
1616
@GeneratedValue(strategy = GenerationType.IDENTITY)
1717
private Long id;

src/main/java/com/manir/springbootecommercerestapi/model/OrderProducts.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
@Data
1212
@Entity
1313
@Table(name = "order_products")
14-
public class OrderProducts {
14+
public class OrderProducts extends BaseEntity{
1515
@Id
1616
@GeneratedValue(strategy = GenerationType.IDENTITY)
1717
private Long id;

src/main/java/com/manir/springbootecommercerestapi/model/Product.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
@Setter
1313
@Entity
1414
@Table(name = "products")
15-
public class Product {
15+
public class Product extends BaseEntity{
1616
@Id
1717
@GeneratedValue(strategy = GenerationType.IDENTITY)
1818
private Long id;

src/main/java/com/manir/springbootecommercerestapi/model/Role.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
@Data
88
@Entity
99
@Table(name = "roles")
10-
public class Role {
10+
public class Role extends BaseEntity{
1111

1212
@Id
1313
@GeneratedValue(strategy = GenerationType.IDENTITY)

src/main/java/com/manir/springbootecommercerestapi/model/User.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = {"userName"}),
1414
@UniqueConstraint(columnNames = {"email"})
1515
})
16-
public class User {
16+
public class User extends BaseEntity{
1717
@Id
1818
@GeneratedValue(strategy = GenerationType.IDENTITY)
1919
private Long id;
@@ -46,4 +46,10 @@ public class User {
4646
fetch = FetchType.LAZY, orphanRemoval = true,
4747
mappedBy = "customer")
4848
private Set<OrderProducts> orderProducts;
49+
50+
//relation with comment or review
51+
@OneToMany(cascade = CascadeType.ALL,
52+
fetch = FetchType.LAZY, orphanRemoval = true,
53+
mappedBy = "customer")
54+
private Set<Comment> comments;
4955
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package com.manir.springbootecommercerestapi.repository;
22

33
import com.manir.springbootecommercerestapi.model.Comment;
4+
import com.manir.springbootecommercerestapi.model.User;
45
import org.springframework.data.jpa.repository.JpaRepository;
56

67
import java.util.List;
78

89
public interface CommentRepository extends JpaRepository<Comment, Long> {
910
List<Comment> findByProductId(Long productId);
11+
List<Comment> findByCustomer(User customer);
1012
}

src/main/java/com/manir/springbootecommercerestapi/service/CommentService.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33

44
import com.manir.springbootecommercerestapi.dto.CommentDto;
5+
import com.manir.springbootecommercerestapi.model.User;
56

67
import java.util.List;
78

89
public interface CommentService {
910

10-
CommentDto createComment(Long productId, CommentDto commentDto);
11+
CommentDto createComment(User customer, Long productId, CommentDto commentDto);
1112

13+
List<CommentDto> findCommentByCustomer(User customer);
1214
List<CommentDto> getAllComments();
1315
List<CommentDto> getAllCommentsByProductId(Long productId);
1416
CommentDto getCommentById(Long productId, Long commentId);

src/main/java/com/manir/springbootecommercerestapi/service/Impl/CommentServiceImpl.java

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
import com.manir.springbootecommercerestapi.dto.CommentDto;
44
import com.manir.springbootecommercerestapi.exception.EcommerceApiException;
55
import com.manir.springbootecommercerestapi.exception.ResourceNotFoundException;
6+
import com.manir.springbootecommercerestapi.model.User;
67
import com.manir.springbootecommercerestapi.repository.CommentRepository;
78
import com.manir.springbootecommercerestapi.repository.ProductRepository;
89
import com.manir.springbootecommercerestapi.model.Comment;
910
import com.manir.springbootecommercerestapi.model.Product;
11+
import com.manir.springbootecommercerestapi.repository.UserRepository;
1012
import com.manir.springbootecommercerestapi.service.CommentService;
1113
import org.modelmapper.ModelMapper;
1214
import org.springframework.http.HttpStatus;
@@ -25,22 +27,37 @@ public class CommentServiceImpl implements CommentService {
2527
private CommentRepository commentRepository;
2628
@Resource
2729
private ProductRepository productRepository;
30+
@Resource
31+
private UserRepository userRepository;
2832

2933
@Override
30-
public CommentDto createComment(Long productId, CommentDto commentDto) {
31-
34+
public CommentDto createComment(User customer, Long productId, CommentDto commentDto) {
35+
User user = findCustomerById(customer.getId());
3236
Product product = findProductById(productId);
3337
//convert to entity
3438
Comment comment = mapToEntity(commentDto);
3539
//save to db
3640
comment.setProduct(product);
41+
comment.setCustomer(user);
3742
Comment createdComment = commentRepository.save(comment);
3843
//convert to dto
3944
CommentDto responseComment = mapToDto(createdComment);
4045

4146
return responseComment;
4247
}
4348

49+
@Override
50+
public List<CommentDto> findCommentByCustomer(User customer) {
51+
List<Comment> comments = commentRepository.findByCustomer(customer);
52+
if (comments.size() == 0){
53+
throw new EcommerceApiException("User has no comment or review", HttpStatus.BAD_REQUEST);
54+
}
55+
List<CommentDto> commentDtoList = comments.stream()
56+
.map(comment -> mapToDto(comment))
57+
.collect(Collectors.toList());
58+
return commentDtoList;
59+
}
60+
4461
@Override
4562
public List<CommentDto> getAllComments() {
4663
List<Comment> comments = commentRepository.findAll();
@@ -120,4 +137,8 @@ private Comment findCommentById(Long commentId){
120137
return comment;
121138
}
122139

140+
private User findCustomerById(Long customerId){
141+
User customer = userRepository.findById(customerId).orElseThrow(()->new ResourceNotFoundException("Customer", customerId));
142+
return customer;
143+
}
123144
}

src/main/java/com/manir/springbootecommercerestapi/service/Impl/OrderServiceImpl.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ public class OrderServiceImpl implements OrderService {
4141
@Transactional
4242
public void placeOrder(User customer) {
4343
CartItemResponse cartItemDto = shoppingCartService.findByCustomer(customer);
44+
//set order fields
4445
OrderDto orderDto = setFields(cartItemDto, customer);
4546
//save order to the db
4647
OrderDto savedOrder = saveOrder(orderDto);

0 commit comments

Comments
 (0)