Skip to content
Snippets Groups Projects
Commit a8938d94 authored by quentin.fasler's avatar quentin.fasler
Browse files

add product and purchase

parent a4487bbe
Branches
Tags
No related merge requests found
Showing
with 330 additions and 6 deletions
...@@ -44,6 +44,11 @@ ...@@ -44,6 +44,11 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.16.1</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.hepia.demobdd.controller;
import com.hepia.demobdd.entity.Product;
import com.hepia.demobdd.repository.ProductRepository;
import org.springframework.beans.factory.annotation.*;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping
public List<Product> getAllProducts() {
return productRepository.findAll();
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productRepository.findById(id).orElse(null);
}
}
package com.hepia.demobdd.controller;
import com.hepia.demobdd.dto.PurchaseRequest;
import com.hepia.demobdd.entity.Product;
import com.hepia.demobdd.entity.Purchase;
import com.hepia.demobdd.entity.User;
import com.hepia.demobdd.repository.ProductRepository;
import com.hepia.demobdd.repository.PurchaseRepository;
import com.hepia.demobdd.repository.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/purchases")
public class PurchaseController {
@Autowired
private PurchaseRepository purchaseRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ProductRepository productRepository;
@GetMapping
public List<Purchase> getAllPurchases() {
return purchaseRepository.findAll();
}
@GetMapping("/{id}")
public Purchase getPurchaseById(@PathVariable Long id) {
return purchaseRepository.findById(id).orElse(null);
}
@Transactional
@PostMapping
public ResponseEntity<String> addPurchase(@RequestBody PurchaseRequest purchaseRequest) {
User user = userRepository.findById(purchaseRequest.getUserId())
.orElseThrow(() -> new IllegalArgumentException("Utilisateur non trouvé"));
Product product = productRepository.findById(purchaseRequest.getProductId())
.orElseThrow(() -> new IllegalArgumentException("Produit non trouvé"));
if (product.getStock() < purchaseRequest.getQuantity()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Stock insuffisant pour le produit.");
}
if (purchaseRequest.getQuantity() <= 0) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("La quantité doit être supérieure à 0.");
}
Purchase purchase = new Purchase(user, product, purchaseRequest.getQuantity());
product.setStock(product.getStock() - purchaseRequest.getQuantity());
purchaseRepository.save(purchase);
productRepository.save(product);
return ResponseEntity.status(HttpStatus.CREATED).body("Commande ajoutée avec succès.");
}
}
package com.hepia.demobdd.dto;
public class PurchaseRequest {
private Long userId;
private Long productId;
private int quantity;
//#region getters
public Long getUserId() {
return userId;
}
public Long getProductId() {
return productId;
}
public int getQuantity() {
return quantity;
}
//#endregion
//#region setters
public void setUserId(Long userId) {
this.userId = userId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
//#endregion
}
package com.hepia.demobdd.entity;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(precision = 10, scale = 2)
private BigDecimal price;
private int stock;
//#region getters
public Long getId() {
return id;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public int getStock() {
return stock;
}
//#endregion
//#region setters
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
//#endregion
}
package com.hepia.demobdd.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "purchase")
public class Purchase {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JsonIgnoreProperties("purchases")
private User user;
@ManyToOne
private Product product;
private int quantity;
public Purchase() {
}
public Purchase(User user, Product product, int quantity) {
this.user = user;
this.product = product;
this.quantity = quantity;
}
//#region getters
public Long getId() {
return id;
}
public User getUser() {
return user;
}
public Product getProduct() {
return product;
}
public int getQuantity() {
return quantity;
}
public BigDecimal getTotalAmount() {
return getProduct().getPrice().multiply(BigDecimal.valueOf(getQuantity()));
}
//#endregion
//#region setters
public void setId(Long id) {
this.id = id;
}
public void setUser(User user) {
this.user = user;
}
public void setProduct(Product product) {
this.product = product;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
//#endregion
}
package com.hepia.demobdd.entity; package com.hepia.demobdd.entity;
import jakarta.persistence.Id; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Entity; import jakarta.persistence.*;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import java.util.List;
@Entity @Entity
@Table(name = "user")
public class User { public class User {
@Id @Id
...@@ -14,6 +14,9 @@ public class User { ...@@ -14,6 +14,9 @@ public class User {
private String name; private String name;
private String email; private String email;
@OneToMany(mappedBy = "user")
@JsonIgnoreProperties("user")
private List<Purchase> purchases;
//#region getters //#region getters
public Long getId() { public Long getId() {
...@@ -27,6 +30,10 @@ public class User { ...@@ -27,6 +30,10 @@ public class User {
public String getEmail() { public String getEmail() {
return email; return email;
} }
public List<Purchase> getPurchases() {
return purchases;
}
//#endregion //#endregion
//#region setters //#region setters
...@@ -42,6 +49,10 @@ public class User { ...@@ -42,6 +49,10 @@ public class User {
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
public void setPurchases(List<Purchase> purchases) {
this.purchases = purchases;
}
//#endregion //#endregion
} }
\ No newline at end of file
package com.hepia.demobdd.repository;
import com.hepia.demobdd.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
\ No newline at end of file
package com.hepia.demobdd.repository;
import com.hepia.demobdd.entity.Purchase;
import com.hepia.demobdd.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PurchaseRepository extends JpaRepository<Purchase, Long> {
}
\ No newline at end of file
...@@ -5,3 +5,5 @@ spring.datasource.driver-class-name=org.mariadb.jdbc.Driver ...@@ -5,3 +5,5 @@ spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.flyway.enabled=true spring.flyway.enabled=true
spring.flyway.baseline-on-migrate=true spring.flyway.baseline-on-migrate=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.sql.init.mode=always
\ No newline at end of file
UPDATE product SET stock = 10;
\ No newline at end of file
CREATE TABLE product (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
price DECIMAL(10, 2),
stock INT
);
CREATE TABLE purchase (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT,
product_id BIGINT,
quantity INT,
FOREIGN KEY (user_id) REFERENCES user(id),
FOREIGN KEY (product_id) REFERENCES product(id)
);
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment