Skip to content

Commit

Permalink
feat(customer/addCustomer): update the add customer functionality to …
Browse files Browse the repository at this point in the history
…use NewCustomerDto while adding new customers
  • Loading branch information
ved-asole committed Dec 26, 2024
1 parent 531f327 commit 73734a0
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.vedasole.ekartecommercebackend.exception.ResourceNotFoundException;
import com.vedasole.ekartecommercebackend.payload.ApiResponse;
import com.vedasole.ekartecommercebackend.payload.CustomerDto;
import com.vedasole.ekartecommercebackend.payload.NewCustomerDto;
import com.vedasole.ekartecommercebackend.security.JwtService;
import com.vedasole.ekartecommercebackend.service.service_interface.CustomerService;
import com.vedasole.ekartecommercebackend.service.service_interface.UserService;
Expand Down Expand Up @@ -50,27 +51,27 @@ public class CustomerController {
/**
* Creates a new customer.
*
* @param customerDto the customer data to create
* @param newCustomerDto the customer data to create
* @return a response with the created customer data and links to itself and the list of customers
*/
@PostMapping
public ResponseEntity<EntityModel<CustomerDto>> createCustomer(
@Valid @RequestBody CustomerDto customerDto
@Valid @RequestBody NewCustomerDto newCustomerDto
) {
log.debug("New Customer request received with email : {}", customerDto.getEmail());
log.debug("New Customer request received : {}", customerDto);
log.debug("New Customer request received with email : {}", newCustomerDto.getEmail());
log.debug("New Customer request received : {}", newCustomerDto);
try {
this.customerService.getCustomerByEmail(customerDto.getEmail());
this.userService.getUserByEmail(customerDto.getEmail());
this.customerService.getCustomerByEmail(newCustomerDto.getEmail());
this.userService.getUserByEmail(newCustomerDto.getEmail());
}catch(ResourceNotFoundException re) {
log.debug("No customer with this email found");
} catch (Exception e) {
throw new APIException("A customer with this email already exists");
}

CustomerDto createdCustomer = this.customerService.createCustomer(customerDto);
CustomerDto createdCustomer = this.customerService.createCustomer(newCustomerDto);
log.debug("New Customer created : {}", createdCustomer.getEmail());
String jwt = this.jwtService.generateToken(this.userService.getUserByEmail(customerDto.getEmail()));
String jwt = this.jwtService.generateToken(this.userService.getUserByEmail(newCustomerDto.getEmail()));
Link selfLink = linkTo(methodOn(CustomerController.class).getCustomer(createdCustomer.getCustomerId())).withSelfRel();
Link customersLink = linkTo(methodOn(CustomerController.class).getAllCustomers()).withRel(CUSTOMERS.getValue());
return ResponseEntity
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package com.vedasole.ekartecommercebackend.payload;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIncludeProperties;
import com.vedasole.ekartecommercebackend.entity.Customer;
import com.vedasole.ekartecommercebackend.utility.AppConstant.Role;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.hateoas.server.core.Relation;

import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.validation.constraints.*;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
* DTO for new {@link Customer}
*/
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Relation(itemRelation = "customer", collectionRelation = "customers")
public class NewCustomerDto implements Serializable {

@Serial
private static final long serialVersionUID = -4970632778733952870L;

private long customerId;

@NotBlank(message = "First name is required")
@Size(
min = 3,
max = 20,
message = "First name must be between minimum of 3 characters and maximum of 20 characters"
)
private String firstName;

@NotBlank(message = "Last name is required")
@Size(
min = 3,
max = 20,
message = "Last name must be between minimum of 3 characters " +
"and maximum of 20 characters"
)
private String lastName;

@NotBlank(message = "Email address is required")
@Email(message = "Email address is not valid",
regexp = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"
)
private String email;

@NotBlank(message = "Password cannot be blank")
@Size(
min = 3,
max = 20,
message = "Password must be between minimum of 3 characters " +
"and maximum of 20 characters"
)
private String password;

@NotNull(message = "Phone number is required")
@Pattern(
regexp = "^(\\+\\d{1,3}[- ]?)?\\d{10}$",
message = "Phone number must be a valid 10-digit number"
)
private String phoneNumber;

@NotNull(message = "Role is required")
@Enumerated(EnumType.STRING)
private Role role;

@JsonIncludeProperties({"cartId"})
private ShoppingCartDto shoppingCart;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createdAt;

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.vedasole.ekartecommercebackend.exception.APIException;
import com.vedasole.ekartecommercebackend.exception.ResourceNotFoundException;
import com.vedasole.ekartecommercebackend.payload.CustomerDto;
import com.vedasole.ekartecommercebackend.payload.NewCustomerDto;
import com.vedasole.ekartecommercebackend.repository.CustomerRepo;
import com.vedasole.ekartecommercebackend.repository.ShoppingCartRepo;
import com.vedasole.ekartecommercebackend.repository.UserRepo;
Expand All @@ -26,6 +27,7 @@
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

Expand All @@ -52,7 +54,7 @@ public class CustomerServiceImpl implements CustomerService {
/**
* Creates a new customer and saves it to the database.
*
* @param customerDto the customer data to be saved
* @param newCustomerDto the new customer data to be saved
* @return the created customer with its ID and other details
* @throws APIException if an error occurs while saving the customer
*/
Expand All @@ -62,12 +64,12 @@ public class CustomerServiceImpl implements CustomerService {
@CacheEvict(value = "allCustomers", allEntries = true),
@CacheEvict(value = "allCustomersPage", allEntries = true)
})
public CustomerDto createCustomer(CustomerDto customerDto) {
public CustomerDto createCustomer(@Valid NewCustomerDto newCustomerDto) {
// Create a new user with the role of USER
User user = new User(
customerDto.getEmail(),
passwordEncoder.encode(customerDto.getPassword()),
customerDto.getRole() != null ? customerDto.getRole() : AppConstant.Role.USER
newCustomerDto.getEmail(),
passwordEncoder.encode(newCustomerDto.getPassword()),
newCustomerDto.getRole() != null ? newCustomerDto.getRole() : AppConstant.Role.USER
);
// Save the user to the database
User newUser;
Expand All @@ -79,7 +81,7 @@ public CustomerDto createCustomer(CustomerDto customerDto) {
}

// Create a new customer and set the user to the newly created user
Customer customer = dtoToCustomer(customerDto);
Customer customer = newCustomerDtoToCustomer(newCustomerDto);
customer.setUser(newUser);

// Save the customer to the database
Expand All @@ -93,7 +95,7 @@ public CustomerDto createCustomer(CustomerDto customerDto) {
newCustomer = this.customerRepo.save(newCustomer);
log.debug("Customer saved with id : {}", newCustomer.getEmail());
} catch (Exception e) {
log.error("Failed to save customer: {}", customerDto.getEmail());
log.error("Failed to save customer: {}", newCustomerDto.getEmail());
throw new APIException("Failed to save customer");
}

Expand Down Expand Up @@ -309,6 +311,19 @@ private Customer dtoToCustomer(CustomerDto customerDto){
return customer;
}

/**
* Maps a NewCustomerDto to a Customer.
*
* @param newCustomerDto the NewCustomerDto to be mapped
* @return the mapped Customer
*/
private Customer newCustomerDtoToCustomer(NewCustomerDto newCustomerDto){
User user = new User(newCustomerDto.getEmail(), passwordEncoder.encode(newCustomerDto.getPassword()), newCustomerDto.getRole());
Customer customer = this.modelMapper.map(newCustomerDto, Customer.class);
customer.setUser(user);
return customer;
}

/**
* Maps a Customer to a CustomerDto.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import com.vedasole.ekartecommercebackend.entity.Customer;
import com.vedasole.ekartecommercebackend.entity.User;
import com.vedasole.ekartecommercebackend.payload.CustomerDto;
import com.vedasole.ekartecommercebackend.payload.NewCustomerDto;
import org.springframework.data.domain.Page;

import java.util.List;

public interface CustomerService {

CustomerDto createCustomer(CustomerDto customerDto);
CustomerDto createCustomer(NewCustomerDto newCustomerDto);
CustomerDto updateCustomer(CustomerDto customerDto , Long customerId);
List<CustomerDto> getAllCustomers();
Page<CustomerDto> getAllCustomersByPage(int page, int size, String sortBy, String sortOrder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ void shouldValidateEmailFormatWhenNotValid() {
@Test
void shouldValidatePasswordLengthWhenLessThanMinimum() {
// Given
CustomerDto customerDto = CustomerDto.builder()
NewCustomerDto newCustomerDto = NewCustomerDto.builder()
.customerId(1)
.firstName("John")
.lastName("Doe")
Expand All @@ -145,7 +145,7 @@ void shouldValidatePasswordLengthWhenLessThanMinimum() {
.build();

// When
Set<ConstraintViolation<CustomerDto>> violations = validator.validate(customerDto);
Set<ConstraintViolation<NewCustomerDto>> violations = validator.validate(newCustomerDto);

// Then
assertEquals(1, violations.size());
Expand All @@ -156,7 +156,7 @@ void shouldValidatePasswordLengthWhenLessThanMinimum() {
@Test
void shouldValidatePasswordLengthWhenMoreThanMaximum() {
// Given
CustomerDto customerDto = CustomerDto.builder()
NewCustomerDto newCustomerDto = NewCustomerDto.builder()
.customerId(1)
.firstName("John")
.lastName("Doe")
Expand All @@ -167,7 +167,7 @@ void shouldValidatePasswordLengthWhenMoreThanMaximum() {
.build();

// When
Set<ConstraintViolation<CustomerDto>> violations = validator.validate(customerDto);
Set<ConstraintViolation<NewCustomerDto>> violations = validator.validate(newCustomerDto);

// Then
assertEquals(1, violations.size());
Expand Down Expand Up @@ -267,7 +267,7 @@ void shouldValidatePhoneNumberWhenNotValid() {
@Test
void shouldValidateRoleWhenNull() {
// Given
CustomerDto customerDto = CustomerDto.builder()
NewCustomerDto newCustomerDto = NewCustomerDto.builder()
.customerId(1)
.firstName("John")
.lastName("Doe")
Expand All @@ -278,7 +278,7 @@ void shouldValidateRoleWhenNull() {
.build();

// When
Set<ConstraintViolation<CustomerDto>> violations = validator.validate(customerDto);
Set<ConstraintViolation<NewCustomerDto>> violations = validator.validate(newCustomerDto);

// Then
assertEquals(1, violations.size());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.vedasole.ekartecommercebackend.utility;

import com.vedasole.ekartecommercebackend.entity.User;
import com.vedasole.ekartecommercebackend.payload.CustomerDto;
import com.vedasole.ekartecommercebackend.payload.NewCustomerDto;
import com.vedasole.ekartecommercebackend.security.JwtService;
import com.vedasole.ekartecommercebackend.service.service_interface.CustomerService;
import lombok.Getter;
Expand Down Expand Up @@ -64,7 +64,7 @@ private void generateUserToken() {
}

private void insertNormalUser() {
CustomerDto adminUser = CustomerDto.builder()
NewCustomerDto normalUser = NewCustomerDto.builder()
.customerId(2)
.email(normalUserEmail)
.firstName("Normal")
Expand All @@ -73,7 +73,7 @@ private void insertNormalUser() {
.password(normalUserPassword)
.role(AppConstant.Role.USER)
.build();
customerService.createCustomer(adminUser);
customerService.createCustomer(normalUser);
}

}

0 comments on commit 73734a0

Please sign in to comment.