Skip to content
This repository has been archived by the owner on Dec 7, 2024. It is now read-only.

Commit

Permalink
feat: RESTful API finished, some adjutments needed
Browse files Browse the repository at this point in the history
  • Loading branch information
alexZ7000 committed Oct 10, 2024
1 parent 4750309 commit 7f9c439
Show file tree
Hide file tree
Showing 11 changed files with 258 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,50 @@
package com.example.comerce.core.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.comerce.core.dto.CategoryDTO;
import com.example.comerce.core.entities.Category;
import com.example.comerce.core.entities.Product;
import com.example.comerce.core.services.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/api/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;

@GetMapping
public ResponseEntity<List<Category>> getAllCategories() {
List<Category> categories = categoryService.findAll();
return ResponseEntity.ok(categories);
}

@GetMapping("/{id}")
public ResponseEntity<Category> getCategoryById(@PathVariable UUID id) {
Optional<Category> category = Optional.ofNullable(categoryService.findById(id));
return category.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}

@PostMapping
public ResponseEntity<Category> createCategory(@RequestBody CategoryDTO categoryDTO) {
Category savedCategory = categoryService.save(categoryDTO.toEntity());
return ResponseEntity.ok(savedCategory);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCategory(@PathVariable UUID id) {
categoryService.delete(id);
return ResponseEntity.noContent().build();
}

@PutMapping("/{id}")
public ResponseEntity<Category> updateCategory(@PathVariable UUID id, @RequestBody CategoryDTO categoryDTO) {
Category updatedCategory = categoryService.update(id, categoryDTO.toEntity());
return ResponseEntity.ok(updatedCategory);
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,55 @@
package com.example.comerce.core.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.comerce.core.dto.ProductDTO;
import com.example.comerce.core.entities.Product;
import com.example.comerce.core.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/api/product")
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;

@GetMapping
public ResponseEntity<List<Product>> getAllProducts() {
List<Product> products = productService.findAll();
return ResponseEntity.ok(products);
}

@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable UUID id) {
Optional<Product> product = productService.findById(id);
return product.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}

@GetMapping("/products/{category}/{id}")
public ResponseEntity<Product> getProductByCategoryAndId(@PathVariable String category, @PathVariable UUID id) {
Optional<Product> product = productService.findById(id);
return product.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}

@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody ProductDTO productDTO) {
Product savedProduct = productService.save(productDTO);
return ResponseEntity.ok(savedProduct);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable UUID id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}

@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable UUID id, @RequestBody ProductDTO productDTO) {
Product updatedProduct = productService.update(id, productDTO);
return ResponseEntity.ok(updatedProduct);
}
}
5 changes: 5 additions & 0 deletions src/main/java/com/example/comerce/core/dto/AddressDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public class AddressDTO {
@NotBlank(message = "Bairro não pode estar em branco")
private String neighborhood;

@NotBlank(message = "Complemento não pode estar em branco")
private String complement;

@NotBlank(message = "Cidade não pode estar em branco")
private String city;

Expand All @@ -31,6 +34,7 @@ public Address toEntity() {
address.setPostal_code(this.postal_code);
address.setStreet(this.street);
address.setNumber(this.number);
address.setComplement(this.complement);
address.setNeighborhood(this.neighborhood);
address.setCity(this.city);
address.setState(this.state);
Expand All @@ -42,6 +46,7 @@ public static AddressDTO toDTO(Address address) {
addressDTO.setPostal_code(address.getPostal_code());
addressDTO.setStreet(address.getStreet());
addressDTO.setNumber(address.getNumber());
addressDTO.setComplement(address.getComplement());
addressDTO.setNeighborhood(address.getNeighborhood());
addressDTO.setCity(address.getCity());
addressDTO.setState(address.getState());
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/com/example/comerce/core/dto/CategoryDTO.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
package com.example.comerce.core.dto;

import com.example.comerce.core.entities.Category;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class CategoryDTO {

@Size(min = 10, max = 255, message = "A descrição da categoria deve ter entre 10 e 255 caracteres")
private String description;

public Category toEntity() {
Category category = new Category();
category.setDescription(this.description);
return category;
}

public static CategoryDTO toDTO(CategoryDTO category) {
CategoryDTO categoryDTO = new CategoryDTO();
categoryDTO.setDescription(category.getDescription());
return categoryDTO;
}
}
31 changes: 31 additions & 0 deletions src/main/java/com/example/comerce/core/dto/OrderDTO.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,41 @@
package com.example.comerce.core.dto;

import com.example.comerce.core.entities.Order;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Getter
@Setter
public class OrderDTO {

@NotNull(message = "Data do pedido não pode ser null")
@FutureOrPresent(message = "Data do pedido deve ser no presente ou no futuro")
private Date date;

@Positive(message = "O desconto deve ser um valor positivo")
private double discount;

@Positive(message = "O valor total deve ser um valor positivo")
private double total_price;

public Order toEntity() {
Order order = new Order();
order.setDate(this.date);
order.setDiscount(this.discount);
order.setDiscount(this.total_price);
return order;
}

public static OrderDTO toDTO(OrderDTO order) {
OrderDTO orderDTO = new OrderDTO();
orderDTO.setDate(order.getDate());
orderDTO.setDiscount(order.getDiscount());
orderDTO.setTotal_price(order.getDiscount());
return orderDTO;
}
}
43 changes: 43 additions & 0 deletions src/main/java/com/example/comerce/core/dto/ProductDTO.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,53 @@
package com.example.comerce.core.dto;

import com.example.comerce.core.entities.Product;
import jakarta.validation.constraints.*;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Getter
@Setter
public class ProductDTO {

@NotBlank(message = "O nome do produto não pode estar em branco")
private String name;

@Positive(message = "A quantidade em estoque deve ser positiva")
private int stock_quantity;

@PositiveOrZero(message = "O preço de custo do produto deve ser zero ou positivo")
private double cost_price;

@PositiveOrZero(message = "O preço de venda do produto deve ser zero ou positivo")
private double sell_price;

@FutureOrPresent(message = "A data de criação do produto deve ser no presente ou no futuro")
private Date created_at;

@PositiveOrZero(message = "O preço do produto deve ser zero ou positivo")
private double price;

public Product toEntity() {
Product product = new Product();
product.setName(this.name);
product.setStock_quantity(this.stock_quantity);
product.setCost_price(this.cost_price);
product.setSell_price(this.sell_price);
product.setCreated_at(this.created_at);
product.setPrice(this.price);
return product;
}

public static ProductDTO toDTO(ProductDTO product) {
ProductDTO productDTO = new ProductDTO();
productDTO.setName(product.getName());
productDTO.setStock_quantity(product.getStock_quantity());
productDTO.setCost_price(product.getCost_price());
productDTO.setSell_price(product.getSell_price());
productDTO.setCreated_at(product.getCreated_at());
productDTO.setPrice(product.getPrice());
return productDTO;
}
}
5 changes: 0 additions & 5 deletions src/main/java/com/example/comerce/core/entities/Category.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package com.example.comerce.core.entities;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import lombok.Singular;

import java.util.Set;
import java.util.UUID;
Expand All @@ -19,11 +16,9 @@ public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "category_id", nullable = false, unique = true, updatable = false, length = 36)
@NotNull(message = "Category ID não pode ser null")
private UUID category_id;

@Column
@Size(min = 10, max = 255, message = "A descrição da categoria deve ter entre 10 e 255 caracteres")
private String description;

@ManyToMany(mappedBy = "categories")
Expand Down
8 changes: 0 additions & 8 deletions src/main/java/com/example/comerce/core/entities/Order.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package com.example.comerce.core.entities;

import jakarta.persistence.*;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Getter;
import lombok.Setter;

Expand All @@ -19,24 +16,19 @@ public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "order_id", nullable = false, unique = true, updatable = false, length = 36)
@NotNull(message = "Order ID não pode ser null")
private UUID order_id;

@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;

@Column(nullable = false)
@NotNull(message = "Data do pedido não pode ser null")
@FutureOrPresent(message = "Data do pedido deve ser no presente ou no futuro")
private Date date;

@Column
@Positive(message = "O desconto deve ser um valor positivo")
private double discount;

@Column(nullable = false)
@Positive(message = "O valor total deve ser um valor positivo")
private double total_price;

@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
Expand Down
16 changes: 13 additions & 3 deletions src/main/java/com/example/comerce/core/entities/Product.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import lombok.Getter;
import lombok.Setter;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
Expand All @@ -19,15 +20,24 @@ public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "product_id", nullable = false, unique = true, updatable = false, length = 36)
@NotNull(message = "Product ID não pode ser null")
private UUID product_id;

@Column(nullable = false)
@NotNull(message = "O nome do produto não pode ser null")
private String name;

@Column(nullable = false)
@Positive(message = "O preço do produto deve ser positivo")
private int stock_quantity;

@Column(nullable = false)
private double cost_price;

@Column(nullable = false)
private double sell_price;

@Column(nullable = false)
private Date created_at;

@Column(nullable = false)
private double price;

@ManyToMany
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,36 @@
package com.example.comerce.core.services;

import com.example.comerce.core.entities.Category;
import com.example.comerce.core.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class CategoryService {
@Autowired
private CategoryRepository categoryRepository;

public List<Category> findAll() {
return categoryRepository.findAll();
}

public Category save(Category category) {
return categoryRepository.save(category);
}

public void delete(UUID categoryId) {
categoryRepository.deleteById(categoryId);
}

public Category update(UUID categoryId, Category category) {
category.setCategory_id(categoryId);
return categoryRepository.save(category);
}

public Category findById(UUID categoryId) {
return categoryRepository.findById(categoryId).orElse(null);
}
}
Loading

0 comments on commit 7f9c439

Please sign in to comment.