Skip to content

Commit 1f2c828

Browse files
authored
Merge pull request #35 from UdL-EPS-SoftArch/product
Product
2 parents df39c95 + 60bc348 commit 1f2c828

12 files changed

Lines changed: 922 additions & 116 deletions

File tree

src/main/java/cat/udl/eps/softarch/demo/config/WebSecurityConfig.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exce
3030
.requestMatchers(HttpMethod.GET, "/identity").authenticated()
3131
.requestMatchers(HttpMethod.POST, "/users").anonymous()
3232
.requestMatchers(HttpMethod.POST, "/users/*").denyAll()
33-
.requestMatchers(HttpMethod.POST, "/*").authenticated()
34-
.requestMatchers(HttpMethod.POST, "/*/*").authenticated()
33+
.requestMatchers(HttpMethod.POST, "/*").authenticated() // ← Protege POST /products
34+
35+
.requestMatchers(HttpMethod.POST, "/*/*").authenticated()
3536
.requestMatchers(HttpMethod.PUT, "/*/*").authenticated()
3637
.requestMatchers(HttpMethod.PATCH, "/*/*").authenticated()
3738
.requestMatchers(HttpMethod.DELETE, "/*/*").authenticated()

src/main/java/cat/udl/eps/softarch/demo/domain/Product.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package cat.udl.eps.softarch.demo.domain;
22

3+
import com.fasterxml.jackson.annotation.JsonProperty;
34
import jakarta.persistence.*;
45
import jakarta.validation.constraints.*;
56
import lombok.*;
@@ -25,6 +26,7 @@ public class Product extends UriEntity<Long>{
2526
@Column(unique = true, nullable = false)
2627
private String name;
2728

29+
@org.hibernate.validator.constraints.Length(max = 100)
2830
@Column(length = 100)
2931
private String description;
3032

@@ -43,6 +45,7 @@ public class Product extends UriEntity<Long>{
4345
@PositiveOrZero
4446
private BigDecimal tax;
4547

48+
@JsonProperty("available")
4649
private boolean isAvailable;
4750

4851
private String promotions;
@@ -68,7 +71,8 @@ public class Product extends UriEntity<Long>{
6871

6972
@PositiveOrZero
7073
private Integer pointsCost; // Points needed to redeem this product
71-
74+
75+
@JsonProperty("partOfLoyaltyProgram")
7276
private boolean isPartOfLoyaltyProgram;
7377

7478

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
package cat.udl.eps.softarch.demo.steps;
2+
3+
import cat.udl.eps.softarch.demo.domain.Product;
4+
import cat.udl.eps.softarch.demo.repository.ProductRepository;
5+
import org.springframework.http.MediaType;
6+
7+
import static org.hamcrest.Matchers.hasSize;
8+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
9+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
10+
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
11+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
12+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
13+
import io.cucumber.java.Before;
14+
import io.cucumber.java.en.And;
15+
import io.cucumber.java.en.When;
16+
import org.springframework.beans.factory.annotation.Autowired;
17+
import org.springframework.test.web.servlet.MvcResult;
18+
19+
import java.math.BigDecimal;
20+
import java.util.Map;
21+
22+
23+
public class CreateProductStepDefs {
24+
25+
@Autowired
26+
private StepDefs stepDefs;
27+
28+
public static Product currentProduct;
29+
30+
@Autowired
31+
private ProductRepository productRepository;
32+
33+
@Before
34+
public void setUp(){
35+
//Mirar si es bona practica ficar un step de el RegisterStepDefs
36+
}
37+
38+
/**
39+
* Converteix un Map<String, String> en un Product, mapejant només els camps presents.
40+
*/
41+
private Product fromMap(Map<String, String> data) {
42+
Product p = new Product();
43+
44+
// ⭐ Valores por defecto para campos con validaciones
45+
p.setStock(0);
46+
p.setKcal(0);
47+
p.setCarbs(0);
48+
p.setProteins(0);
49+
p.setFats(0);
50+
p.setAvailable(true); // Disponible por defecto
51+
p.setPartOfLoyaltyProgram(false);
52+
53+
// Sobrescribir con los datos del test
54+
data.forEach((key, value) -> {
55+
if (value == null || value.isBlank()) return;
56+
switch (key) {
57+
case "name" -> p.setName(value);
58+
case "price" -> p.setPrice(new BigDecimal(value));
59+
case "stock" -> p.setStock(Integer.parseInt(value));
60+
case "barcode" -> p.setBarcode(value);
61+
case "rating" -> p.setRating(Double.parseDouble(value));
62+
case "tax" -> p.setTax(new BigDecimal(value));
63+
case "kcal" -> p.setKcal(Integer.parseInt(value));
64+
case "carbs" -> p.setCarbs(Integer.parseInt(value));
65+
case "proteins" -> p.setProteins(Integer.parseInt(value));
66+
case "fats" -> p.setFats(Integer.parseInt(value));
67+
case "pointsGiven" -> p.setPointsGiven(Integer.parseInt(value));
68+
case "pointsCost" -> p.setPointsCost(Integer.parseInt(value));
69+
case "isAvailable" -> p.setAvailable(Boolean.parseBoolean(value));
70+
case "isPartOfLoyaltyProgram" -> p.setPartOfLoyaltyProgram(Boolean.parseBoolean(value));
71+
case "brand" -> p.setBrand(value);
72+
case "description" -> p.setDescription(value);
73+
case "discount" -> p.setDiscount(value);
74+
case "size" -> p.setSize(value);
75+
case "promotions" -> p.setPromotions(value);
76+
default -> System.out.println("⚠️ Campo desconocido: " + key);
77+
}
78+
});
79+
80+
return p;
81+
}
82+
83+
@When("^I register a new product with the following details:$")
84+
public void iRegisterANewProductWithDetails(io.cucumber.datatable.DataTable dataTable) throws Exception {
85+
// Convertir la tabla correctamente (primera fila = headers, segunda = valores)
86+
Map<String, String> productData = dataTable.asMap(String.class, String.class);
87+
88+
// 🔍 DEBUG: Ver qué recibe de Cucumber
89+
System.out.println("📋 Datos recibidos de Cucumber:");
90+
productData.forEach((k, v) -> System.out.println(" " + k + " = " + v));
91+
92+
currentProduct = fromMap(productData);
93+
94+
// 🔍 DEBUG
95+
String jsonBody = stepDefs.mapper.writeValueAsString(currentProduct);
96+
System.out.println("📤 JSON enviado: " + jsonBody);
97+
98+
var requestBuilder = post("/products")
99+
.contentType(MediaType.APPLICATION_JSON)
100+
.content(jsonBody)
101+
.accept(MediaType.APPLICATION_JSON);
102+
103+
if (AuthenticationStepDefs.currentUsername != null) {
104+
requestBuilder = requestBuilder.with(AuthenticationStepDefs.authenticate());
105+
}
106+
107+
stepDefs.result = stepDefs.mockMvc.perform(requestBuilder).andDo(print());
108+
109+
// 🔍 DEBUG
110+
MvcResult mvcresult = stepDefs.result.andReturn();
111+
String responseBody = mvcresult.getResponse().getContentAsString();
112+
System.out.println("📥 Respuesta: " + responseBody);
113+
}
114+
115+
@And("^The product with name \"([^\"]*)\" is registered$")
116+
public void theProductWithNameIsRegistered(String productName) throws Exception {
117+
118+
if (productRepository.findByName(productName).isEmpty()) {
119+
Product product = new Product();
120+
product.setName(productName);
121+
productRepository.save(product);
122+
}
123+
124+
}
125+
126+
@And("^The product with name \"([^\"]*)\" is not registered$")
127+
public void theProductWithNameIsNotRegistered(String productName) throws Exception {
128+
stepDefs.result = stepDefs.mockMvc.perform(
129+
get("/products/search/findByName")
130+
.param("name", productName)
131+
.accept(MediaType.APPLICATION_JSON)
132+
.with(AuthenticationStepDefs.authenticate()))
133+
.andExpect(status().isOk())
134+
.andExpect(jsonPath("$._embedded.products", hasSize(0))); // Solo 1
135+
}
136+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package cat.udl.eps.softarch.demo.steps;
2+
3+
import cat.udl.eps.softarch.demo.domain.Product;
4+
import cat.udl.eps.softarch.demo.repository.ProductRepository;
5+
import io.cucumber.java.en.When;
6+
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.http.MediaType;
9+
import org.springframework.transaction.annotation.Transactional;
10+
11+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
12+
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
13+
14+
@Transactional
15+
public class DeleteProductStepDefs {
16+
17+
@Autowired
18+
private StepDefs stepDefs;
19+
20+
@Autowired
21+
private ProductRepository productRepository;
22+
23+
public static Product currentProduct;
24+
25+
@When("^I delete the product with id \"([^\"]*)\"$")
26+
public void iRequestTheProductWithId(String id) throws Exception {
27+
28+
var requestBuilder = delete("/products/" + id)
29+
.accept(MediaType.APPLICATION_JSON);
30+
31+
if (AuthenticationStepDefs.currentUsername != null) {
32+
requestBuilder = requestBuilder.with(AuthenticationStepDefs.authenticate());
33+
}
34+
35+
stepDefs.result = stepDefs.mockMvc.perform(requestBuilder).andDo(print());
36+
37+
}
38+
39+
40+
}

src/test/java/cat/udl/eps/softarch/demo/steps/ProductStepDefs.java

Lines changed: 0 additions & 77 deletions
This file was deleted.

0 commit comments

Comments
 (0)