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
3 changes: 2 additions & 1 deletion 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,7 @@ public class Customer extends User {
@NotEmpty
private String phoneNumber;


@Override
@JsonValue(value = false)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
Expand All @@ -40,4 +41,4 @@ public Collection<? extends GrantedAuthority> getAuthorities() {
//TODO
// @OneToOne
// private Loyalty loyalty;
}
}
3 changes: 3 additions & 0 deletions src/main/java/cat/udl/eps/softarch/demo/domain/Loyalty.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cat.udl.eps.softarch.demo.domain;

import com.fasterxml.jackson.annotation.JsonIdentityReference;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
Expand All @@ -25,10 +26,12 @@ public class Loyalty extends UriEntity<Long> {

@NotNull
@ManyToOne
@JsonIdentityReference(alwaysAsId = true)
private Customer customer;

@NotNull
@ManyToOne
@JsonIdentityReference(alwaysAsId = true)
private Business business;

@NotNull
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
Expand Up @@ -92,19 +92,19 @@ public void thereIsALoyaltyForCustomerAndBusinessWithPoints(
@When("I create a loyalty for customer {string} and business {string} with {int} points")
public void iCreateALoyaltyForCustomerAndBusinessWithPoints(
String customerUsername, String businessId, Integer points) throws Exception {
Customer customer = customerRepository.findById(customerUsername).orElseThrow();
Customer customer = customerRepository.findByName(customerUsername).getFirst();
Business business = businessRepository.findById(businessId).orElseThrow();

JSONObject loyalty = new JSONObject();
loyalty.put("startDate", ZonedDateTime.now().toString());
loyalty.put("accumulatedPoints", points);
loyalty.put("customer", "/customers/" + customerUsername);
loyalty.put("business", "/businesses/" + businessId);
Loyalty loyalty = new Loyalty();
loyalty.setAccumulatedPoints(points);
loyalty.setCustomer(customer);
loyalty.setBusiness(business);
loyalty.setStartDate(ZonedDateTime.now());

stepDefs.result = stepDefs.mockMvc.perform(
post("/loyalties")
.contentType(MediaType.APPLICATION_JSON)
.content(loyalty.toString())
.content(stepDefs.mapper.writeValueAsString(loyalty))
.characterEncoding(StandardCharsets.UTF_8)
.accept(MediaType.APPLICATION_JSON)
.with(AuthenticationStepDefs.authenticate()))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
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 {string} to have {int} points")
public void iUpdateTheLoyaltyForCustomerAndBusinessToHavePoints(
String customerUsername, String businessUsername, Integer newPoints) throws Exception {

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

List<Loyalty> loyalties = loyaltyRepository.findByCustomerAndBusiness(customer, business);
assertFalse(loyalties.isEmpty(), "Loyalty should exist before updating");
Loyalty loyalty = loyalties.getFirst();
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());
}
}
2 changes: 1 addition & 1 deletion src/test/resources/features/RegisterCustomer.feature
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Feature: Register Customer
Given There is a registered customer with username "customer1" and password "password" and email "customer1@example.com" and phoneNumber "123456789"
And I'm not logged in
When I register a new customer with username "customer1" and password "newpass" and email "customer2@example.com" and phoneNumber "987654321"
Then The response code is 400
Then The response code is 409

Scenario: Register customer without username
Given I'm not logged in
Expand Down
24 changes: 24 additions & 0 deletions src/test/resources/features/UpdateLoyalty.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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"
And There is a registered business with id "testbusiness" and name "Test Business" and address "123 Main St"
And There is a loyalty for customer "customer1" and business "testbusiness" with 50 points
And I login as "customer1" with password "password"

Scenario: Update loyalty points successfully
When I update the loyalty for customer "customer1" and business "testbusiness" 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 "testbusiness" 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