Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exce
.requestMatchers(HttpMethod.GET, "/businesses", "/businesses/**").permitAll()
.requestMatchers(HttpMethod.GET, "/products", "/products/**").permitAll() // <-- NUEVO: Ver productos es público
.requestMatchers(HttpMethod.POST, "/users").anonymous()
.requestMatchers(HttpMethod.POST, "/customers").anonymous()
.requestMatchers(HttpMethod.POST, "/customers").permitAll()

// Endpoints Bloqueados Específicamente
.requestMatchers(HttpMethod.POST, "/users/*").denyAll()
Expand Down

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to develop a custom CustomerController for Customer registration. The CustomerRepository already provides and enpoint at POST /customers
Check the approach followed to register users for similar functionality.
And if you need to customise something before or after creating a new customer, you can use the CustomerEventHandler.

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cat.udl.eps.softarch.demo.controller;

import cat.udl.eps.softarch.demo.domain.Customer;
import cat.udl.eps.softarch.demo.repository.CustomerRepository;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("/customers")
public class CustomerController {

private final CustomerRepository customerRepository;

public CustomerController(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}

@PostMapping
public Customer register(@RequestBody Customer customer) {
customer.encodePassword(); // 🔐 CLAVE
customer.setRoles(Set.of("CUSTOMER")); // 🔑 CLAVE
return customerRepository.save(customer);
}
}
7 changes: 7 additions & 0 deletions src/main/java/cat/udl/eps/softarch/demo/domain/Customer.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ public class Customer extends User {
@NotEmpty
private String phoneNumber;

// Asegurar que el ID sea el email
@Override
public void setEmail(String email) {
super.setEmail(email);
this.setId(email);
}

@Override
@JsonValue(value = false)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ public CustomerEventHandler(CustomerRepository customerRepository) {
@HandleBeforeCreate
public void handleCustomerPreCreate(Customer customer) {
logger.info("Before creating: {}", customer.toString());
// Codificar password ANTES de crear
if (customer.getPassword() != null && !customer.getPassword().isEmpty()) {
customer.encodePassword();
}
}

@HandleBeforeSave
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package cat.udl.eps.softarch.demo.steps;

import cat.udl.eps.softarch.demo.domain.Business;
import cat.udl.eps.softarch.demo.domain.Customer;
import cat.udl.eps.softarch.demo.domain.Loyalty;
import cat.udl.eps.softarch.demo.repository.BusinessRepository;
import cat.udl.eps.softarch.demo.repository.CustomerRepository;
import cat.udl.eps.softarch.demo.repository.LoyaltyRepository;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

public class UpdateLoyaltyStepDefs {

@Autowired
private StepDefs stepDefs;

@Autowired
private LoyaltyRepository loyaltyRepository;

@Autowired
private CustomerRepository customerRepository;

@Autowired
private BusinessRepository businessRepository;

private Long loyaltyId;

@When("I update the loyalty for customer {string} and business {Long} to have {int} points")
public void iUpdateTheLoyaltyForCustomerAndBusinessToHavePoints(
String customerUsername, String businessId, Integer newPoints) throws Exception {

Customer customer = customerRepository.findById(customerUsername).orElseThrow();
Business business = businessRepository.findById(businessId).orElseThrow();

List<Loyalty> loyalties = loyaltyRepository.findByCustomerAndBusiness(customer, business);
assertTrue(!loyalties.isEmpty(), "Loyalty should exist before updating");
Loyalty loyalty = loyalties.get(0);
loyaltyId = loyalty.getId();

JSONObject loyaltyUpdate = new JSONObject();
loyaltyUpdate.put("accumulatedPoints", newPoints);

stepDefs.result = stepDefs.mockMvc.perform(
patch("/loyalties/{id}", loyaltyId)
.contentType(MediaType.APPLICATION_JSON)
.content(loyaltyUpdate.toString())
.characterEncoding(StandardCharsets.UTF_8)
.accept(MediaType.APPLICATION_JSON)
.with(AuthenticationStepDefs.authenticate()))
.andDo(print());
}

@When("I update the loyalty with id {long} to have {int} points")
public void iUpdateTheLoyaltyWithIdToHavePoints(Long id, Integer newPoints) throws Exception {
JSONObject loyaltyUpdate = new JSONObject();
loyaltyUpdate.put("accumulatedPoints", newPoints);

stepDefs.result = stepDefs.mockMvc.perform(
patch("/loyalties/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.content(loyaltyUpdate.toString())
.characterEncoding(StandardCharsets.UTF_8)
.accept(MediaType.APPLICATION_JSON)
.with(AuthenticationStepDefs.authenticate()))
.andDo(print());
}

@And("The loyalty has {int} accumulated points")
public void theLoyaltyHasAccumulatedPoints(Integer expectedPoints) throws Exception {
// Verificamos que el último resultado contenga los puntos esperados
stepDefs.result.andExpect(jsonPath("$.accumulatedPoints", is(expectedPoints)));
}

@Given("There is no loyalty with id {long}")
public void thereIsNoLoyaltyWithId(Long id) {
assertFalse(loyaltyRepository.existsById(id),
"Loyalty with id \"" + id + "\" shouldn't exist");
}
}
27 changes: 27 additions & 0 deletions src/test/resources/features/UpdateLoyalty.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Feature: Update Loyalty
In order to manage loyalty program progress
As a business
I want to update existing loyalty records

Background:
Given There is a registered customer with username "customer1" and password "password" and email "customer1@example.com"
Given There is a registered business with id 1 and name "Test Business" and address "123 Main St"
And There is a loyalty for customer "customer1" and business 1 with 50 points


And I login as "customer1" with password "password"
And There is a loyalty for customer "customer1" and business 1 with 50 points

Scenario: Update loyalty points successfully
When I update the loyalty for customer "customer1" and business 1 to have 120 points
Then The response code is 200
And The loyalty has 120 accumulated points

Scenario: Update loyalty points to a negative value fails
When I update the loyalty for customer "customer1" and business 1 to have -30 points
Then The response code is 400

Scenario: Update non-existent loyalty fails
Given There is no loyalty with id 999
When I update the loyalty with id 999 to have 200 points
Then The response code is 404
Loading