Compare commits

21 Commits
main ... main

Author SHA1 Message Date
c0599b91c9 Merge remote-tracking branch 'origin/main' 2025-06-13 20:01:59 +02:00
fa30672977 ajout des reviews 2025-06-13 20:01:43 +02:00
3b42e4aaf9 Correction 2025-06-13 19:34:46 +02:00
81ae9faba6 J'avais oublié quelques tests a tester, et j'ai résolu un bug sans savoir comment, mais c'est résolu 2025-06-13 17:19:00 +02:00
e3f6f30fb6 Merge pull request 'Order terminé' (#1) from Order into main
Reviewed-on: pietrois/mylibrary#1
2025-06-13 16:47:36 +02:00
bfefc92360 Finalisation de Order 2025-06-13 16:40:51 +02:00
2a5cbbd745 Sauvegarde de l'avancée 2025-06-13 06:52:41 +02:00
d5049671e6 Sauvegarde de l'avancée 2025-06-12 19:24:21 +02:00
d522d0dad1 ajout des tests des exceptions 2025-06-12 10:26:07 +02:00
7d31067021 Merge remote-tracking branch 'origin/main' into Order 2025-06-11 21:52:40 +02:00
219b924efa Merge remote-tracking branch 'origin/main' 2025-06-11 15:41:24 +02:00
e06a0b3b3c correction de bug et upgrade du BDD 2025-06-11 15:40:58 +02:00
276b6e4fc6 Sauvegarde de l'avancée 2025-06-11 00:15:23 +02:00
d71ffcc9ff Merge branch 'main' of https://grond.iut-fbleau.fr/pietrois/mylibrary 2025-06-10 22:50:11 +02:00
568d67a437 Faut ca pour merge je sais pas pourquoi 2025-06-10 22:49:26 +02:00
f6e560f23b Feature Book 2025-06-10 22:44:17 +02:00
8f76a6fbd4 subscription passe ! 2025-06-09 22:52:27 +02:00
0bb4a21c95 Merge remote-tracking branch 'origin/main' 2025-06-09 14:21:58 +02:00
9d49b597e9 J'avais oublié des customer dans book 2025-06-07 20:09:43 +02:00
fedaecda21 J'avais oublié des customer dans book 2025-06-07 14:52:44 +02:00
c2208d010b BookUseCaseTest fait ? 2025-06-07 14:46:56 +02:00
90 changed files with 6051 additions and 3 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

7
.idea/encodings.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

12
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_23" default="true" project-jdk-name="openjdk-23" project-jdk-type="JavaSDK" />
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,23 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book;
import lombok.Builder;
import lombok.Getter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
@Builder
@Getter
public class BookDTO {
private final String isbn;
private final String title;
private final String author;
private final String publisher;
private final Date date;
private final double price;
private final int initialStock;
private final ArrayList<String> categories;
private final String description;
private final String language;
}

View File

@@ -0,0 +1,17 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book;
import java.util.ArrayList;
import java.util.Date;
public record BookInfo(String isbn,
String title,
String author,
String publisher,
Date date,
double price,
int initialStock,
ArrayList<String>categories,
String description,
String language){
}

View File

@@ -0,0 +1,44 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.converter;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
public final class BookConverter {
private BookConverter(){
}
public static Book toDomain(BookInfo newBook) {
return Book.builder()
.isbn(newBook.isbn())
.title(newBook.title())
.author(newBook.author())
.publisher(newBook.publisher())
.date(newBook.date())
.price(newBook.price())
.initialStock(newBook.initialStock())
.categories(newBook.categories())
.description(newBook.description())
.language(newBook.language())
.build();
}
public static BookDTO toDTO(Book book) {
return BookDTO.builder()
.isbn(book.getIsbn())
.title(book.getTitle())
.author(book.getAuthor())
.publisher(book.getPublisher())
.date(book.getDate())
.price(book.getPrice())
.initialStock(book.getInitialStock())
.categories(book.getCategories())
.description(book.getDescription())
.language(book.getLanguage())
.build();
}
}

View File

@@ -0,0 +1,37 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.entity;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.IllegalBookStockException;
import lombok.Builder;
import lombok.Getter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
@Builder
@Getter
public class Book {
private String isbn;
private String title;
private String author;
private String publisher;
private Date date;
private double price;
private int initialStock;
private ArrayList<String> categories;
private String description;
private String language;
public void removeStock(int stockToRemove) throws IllegalBookStockException{
if (initialStock - stockToRemove <0){ throw new IllegalBookStockException(stockToRemove,initialStock); }
initialStock = initialStock - stockToRemove;
}
public void addStock(int stockToAdd) {
initialStock = initialStock + stockToAdd;
}
}

View File

@@ -0,0 +1,13 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import java.text.MessageFormat;
import java.util.UUID;
public class BookNotFoundException extends Exception {
public static final String THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE = "Book not found: {0}";
public BookNotFoundException(String isbn) {
super(MessageFormat.format(THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE, isbn));
}
}

View File

@@ -0,0 +1,13 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import java.text.MessageFormat;
public class IllegalBookStockException extends Exception {
public static final String CANNOT_REMOVE_STOCK = "Cannot remove {0} stock from {1} stock";
public IllegalBookStockException(int needed, int actual) {
super(MessageFormat.format(CANNOT_REMOVE_STOCK, needed,
actual));
}
}

View File

@@ -0,0 +1,8 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
public class NotValidBookException extends Exception {
public NotValidBookException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,55 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.repository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import lombok.NoArgsConstructor;
import javax.swing.text.html.Option;
@NoArgsConstructor
public final class BookRepository {
private final List<Book> books = new ArrayList<>();
public List<Book> findAll() {
return books;
}
public void deleteAll() {
books.clear();
}
public Book save(Book newBook) {
for (Book book: books) {
if (book.getIsbn().equals(newBook.getIsbn())){
books.remove(book);
break;
}
}
this.books.add(newBook);
return newBook;
}
public Optional<Book> findByISBN(String isbn) {
for (Book book:books) {
System.out.println(book.getIsbn());
if(book.getIsbn().equals(isbn)){
return Optional.of(book);
}
}
return Optional.empty();
}
public boolean existsByISBN(String isbn) {
return this.books.stream()
.anyMatch(book -> book.getIsbn().equals(isbn));
}
public void delete(Book book) {
this.books.remove(book);
}
}

View File

@@ -0,0 +1,85 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.usecase;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.converter.BookConverter;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.IllegalBookStockException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.validator.BookValidator;
import java.util.Optional;
import java.util.UUID;
public final class BookUseCase {
private final BookRepository bookRepository;
public BookUseCase(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public String registerBook(BookInfo newBook) throws NotValidBookException {
BookValidator.validate(newBook);
Book bookToRegister = BookConverter.toDomain(newBook);
bookRepository.save(bookToRegister);
return bookToRegister.getIsbn();
}
public Optional<BookDTO> findBookByISBN(String isbn) {
System.out.println(bookRepository.findAll().size());
Optional<Book> optionalBook = bookRepository.findByISBN(isbn);
return optionalBook.map(BookConverter::toDTO);
}
public BookDTO updateBook(String isbn, BookInfo bookInfo)
throws BookNotFoundException, NotValidBookException {
BookValidator.validate(bookInfo);
Book bookByISBN = getBookIfDoesNotExistThrowBookNotFoundException(
isbn);
Book book = Book.builder()
.isbn(isbn)
.title(bookInfo.title())
.author(bookInfo.author())
.publisher(bookInfo.publisher())
.date(bookInfo.date())
.price(bookInfo.price())
.initialStock(bookInfo.initialStock())
.categories(bookInfo.categories())
.description(bookInfo.description())
.language(bookInfo.language())
.build();
Book updatedBook = bookRepository.save(book);
return BookConverter.toDTO(updatedBook);
}
public void deleteBook(String isbn) throws BookNotFoundException {
Book bookToDelete = getBookIfDoesNotExistThrowBookNotFoundException(isbn);
this.bookRepository.delete(bookToDelete);
}
public int addStock(String isbn, int stockToAdd) throws BookNotFoundException {
Book bookToAddStock = getBookIfDoesNotExistThrowBookNotFoundException(isbn);
bookToAddStock.addStock(stockToAdd);
bookRepository.save(bookToAddStock);
return bookToAddStock.getInitialStock();
}
public int subtractStock(String isbn, int loyaltyPointToRemove)
throws BookNotFoundException, IllegalBookStockException {
Book bookToSubtractStock = getBookIfDoesNotExistThrowBookNotFoundException(isbn);
bookToSubtractStock.removeStock(loyaltyPointToRemove);
bookRepository.save(bookToSubtractStock);
return bookToSubtractStock.getInitialStock();
}
private Book getBookIfDoesNotExistThrowBookNotFoundException(String isbn)
throws BookNotFoundException {
Optional<Book> optionalBookById = bookRepository.findByISBN(isbn);
if (optionalBookById.isEmpty()) {
throw new BookNotFoundException(isbn);
}
return optionalBookById.get();
}
}

View File

@@ -0,0 +1,74 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.validator;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
public final class BookValidator {
public static final String ISBN_IS_NOT_VALID = "ISBN is not valid";
public static final String ISBN_CANNOT_BE_BLANK = "ISBN cannot be blank";
public static final String TITLE_CANNOT_BE_BLANK = "Title cannot be blank";
public static final String AUTHOR_CANNOT_BE_BLANK = "Author cannot be blank";
public static final String PUBLISHER_CANNOT_BE_BLANK = "Publisher cannot be blank";
public static final String PRICE_CANNOT_BE_NEGATIVE = "Price cannot be negative";
public static final String PRICE_CANNOT_BE_EQUAL_TO_ZERO = "Price cannot be equal to zero";
public static final String INITIAL_STOCK_CANNOT_BE_NEGATIVE = "Stock cannot be negative";
public static final String ISBN_REGEX = "\\d{13}";
private BookValidator() {
}
public static void validate(BookInfo newBook) throws NotValidBookException {
validateAuthor(newBook);
validateTitle(newBook);
validatePublisher(newBook);
validateISBN(newBook);
validatePrice(newBook);
validateInitialStock(newBook);
}
private static void validateISBN(BookInfo newBook)
throws NotValidBookException {
if (newBook.isbn().isBlank()) {
throw new NotValidBookException(ISBN_CANNOT_BE_BLANK);
}
if (!newBook.isbn().matches(ISBN_REGEX)) {
throw new NotValidBookException(ISBN_IS_NOT_VALID);
}
}
private static void validateTitle(BookInfo newBook) throws NotValidBookException {
if (newBook.title().isBlank()) {
throw new NotValidBookException(TITLE_CANNOT_BE_BLANK);
}
}
private static void validateAuthor(BookInfo newBook) throws NotValidBookException {
if (newBook.author().isBlank()) {
throw new NotValidBookException(AUTHOR_CANNOT_BE_BLANK);
}
}
private static void validatePublisher(BookInfo newBook) throws NotValidBookException {
if (newBook.publisher().isBlank()){
throw new NotValidBookException(PUBLISHER_CANNOT_BE_BLANK);
}
}
private static void validatePrice(BookInfo newBook) throws NotValidBookException {
if (newBook.price() < 0){
throw new NotValidBookException(PRICE_CANNOT_BE_NEGATIVE);
} else if (newBook.price() == 0){
throw new NotValidBookException(PRICE_CANNOT_BE_EQUAL_TO_ZERO);
}
}
private static void validateInitialStock(BookInfo newBook) throws NotValidBookException {
if (newBook.initialStock() < 0){
throw new NotValidBookException(INITIAL_STOCK_CANNOT_BE_NEGATIVE);
}
}
}

View File

@@ -8,6 +8,7 @@ import lombok.Getter;
@Builder
@Getter
public class Customer {
private UUID id;
private String firstName;

View File

@@ -20,15 +20,23 @@ public final class CustomerRepository {
}
public Customer save(Customer newCustomer) {
Optional<Customer> optionalCustomerWithSameId = this.findById(newCustomer.getId());
optionalCustomerWithSameId.ifPresentOrElse(customers::remove, newCustomer::setRandomUUID);
if (newCustomer.getId() == null) {
newCustomer.setRandomUUID();
}
this.findById(newCustomer.getId()).ifPresent(customers::remove);
this.customers.add(newCustomer);
return newCustomer;
}
public Optional<Customer> findById(UUID uuid) {
if (uuid == null) {
return Optional.empty();
}
return this.customers.stream()
.filter(customer -> customer.getId().equals(uuid))
.filter(customer -> uuid.equals(customer.getId()))
.findFirst();
}

View File

@@ -0,0 +1,13 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order;
import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
public class AddressDTO {
private final String street;
private final String city;
private final String postalCode;
private final String country;
}

View File

@@ -0,0 +1,19 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order;
import lombok.Builder;
import lombok.Getter;
import java.util.List;
import java.util.UUID;
@Builder
@Getter
public class OrderDTO {
private final UUID id;
private final UUID customerId;
private final List<OrderLineDTO> orderLines;
private final double totalPrice;
private final double totalPriceToPay;
private final AddressDTO address;
private final PaymentMethod paymentMethod;
}

View File

@@ -0,0 +1,17 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.UUID;
@Getter
@Setter
@Builder
public class OrderInfo {
private UUID customerId;
private List<OrderLineDTO> orderLines;
private AddressDTO address;
private String paymentMethod;
}

View File

@@ -0,0 +1,11 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order;
import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
public class OrderLineDTO {
private final String bookId;
private final int quantity;
}

View File

@@ -0,0 +1,6 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order;
public enum PaymentMethod {
CREDIT_CARD,
LOYALTY_POINTS
}

View File

@@ -0,0 +1,35 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.converter;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderLineDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.order.AddressDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.order.PaymentMethod;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.order.entity.Order;
public class OrderConverter {
private OrderConverter() {
}
public static Order toDomain(OrderInfo orderInfo) {
return Order.builder()
.customerId(orderInfo.getCustomerId())
.orderLines(orderInfo.getOrderLines())
.address(orderInfo.getAddress())
.paymentMethod(PaymentMethod.valueOf(orderInfo.getPaymentMethod()))
.build();
}
public static OrderDTO toDTO(Order order) {
return OrderDTO.builder()
.id(order.getId())
.customerId(order.getCustomerId())
.orderLines(order.getOrderLines())
.totalPrice(order.getTotalPrice())
.totalPriceToPay(order.getTotalPriceToPay())
.address(order.getAddress())
.paymentMethod(order.getPaymentMethod())
.build();
}
}

View File

@@ -0,0 +1,27 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.entity;
import fr.iut_fbleau.but3.dev62.mylibrary.order.*;
import fr.iut_fbleau.but3.dev62.mylibrary.order.exception.NotValidOrderException;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.UUID;
@Setter
@Getter
@Builder
public class Order {
private UUID id;
private UUID customerId;
private List<OrderLineDTO> orderLines;
private double totalPrice;
private double totalPriceToPay;
private AddressDTO address;
private PaymentMethod paymentMethod;
public void setRandomUUID() {
this.id = UUID.randomUUID();
}
}

View File

@@ -0,0 +1,7 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.exception;
public class NotValidOrderException extends Exception {
public NotValidOrderException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,13 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.exception;
import java.text.MessageFormat;
import java.util.UUID;
public class OrderNotFoundException extends Exception {
public static final String THE_ORDER_WITH_ID_DOES_NOT_EXIST_MESSAGE = "The order with id {0} does not exist";
public OrderNotFoundException(String message) {
super(MessageFormat.format(THE_ORDER_WITH_ID_DOES_NOT_EXIST_MESSAGE, message));
}
}

View File

@@ -0,0 +1,9 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,49 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.repository;
import fr.iut_fbleau.but3.dev62.mylibrary.order.entity.Order;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public final class OrderRepository {
private final List<Order> orders = new ArrayList<>();
public List<Order> findAll() {
return orders;
}
public Order save(Order newOrder) {
Optional<Order> optionalOrderWithSameId = this.findById(newOrder.getId());
optionalOrderWithSameId.ifPresent(orders::remove);
if (newOrder.getId() == null) {
newOrder.setRandomUUID();
}
this.orders.add(newOrder);
return newOrder;
}
public Optional<Order> findById(UUID uuid) {
return this.orders.stream()
.filter(order -> order.getId().equals(uuid))
.findFirst();
}
public List<Order> findByCustomerId(UUID customerId) {
List<Order> result = new ArrayList<>();
for (Order order : orders) {
if (order.getCustomerId().equals(customerId)) {
result.add(order);
}
}
return result;
}
public boolean existsById(UUID uuid) {
return this.orders.stream()
.anyMatch(order -> order.getId().equals(uuid));
}
}

View File

@@ -0,0 +1,193 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.usecase;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.IllegalBookStockException;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.IllegalCustomerPointException;
import fr.iut_fbleau.but3.dev62.mylibrary.order.entity.Order;
import fr.iut_fbleau.but3.dev62.mylibrary.order.usecase.OrderUseCase;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderLineDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.order.AddressDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.order.PaymentMethod;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.order.repository.OrderRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.order.converter.OrderConverter;
import fr.iut_fbleau.but3.dev62.mylibrary.order.validator.OrderValidator;
import fr.iut_fbleau.but3.dev62.mylibrary.order.exception.NotValidOrderException;
import fr.iut_fbleau.but3.dev62.mylibrary.order.exception.OrderNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.order.exception.UserNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.repository.CustomerRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
import java.util.*;
import java.util.stream.Collectors;
public class OrderUseCase {
private final OrderRepository orderRepository;
private final BookRepository bookRepository;
private final CustomerRepository customerRepository;
private OrderInfo tempOrderInfo;
private List<OrderLineDTO> tempOrderLines;
private AddressDTO tempAddress;
public OrderUseCase(OrderRepository orderRepository, BookRepository bookRepository, CustomerRepository customerRepository) {
this.orderRepository = orderRepository;
this.bookRepository = bookRepository;
this.customerRepository = customerRepository;
}
public void registerOrderInfo(OrderInfo orderInfo) {
this.tempOrderInfo = orderInfo;
}
public void addBooksToOrder(List<OrderLineDTO> orderLines) throws NotValidOrderException {
this.tempOrderLines = orderLines;
}
public void setDeliveryAddress(AddressDTO address) {
this.tempAddress = address;
}
private double computeTotalPrice(List<OrderLineDTO> orderInfo) throws NotValidOrderException {
if (orderInfo == null || orderInfo.isEmpty()) {
throw new NotValidOrderException("Order lines cannot be null or empty");
}
double totalPrice = 0.0;
for (OrderLineDTO line : orderInfo) {
Book book = bookRepository.findByISBN(line.getBookId())
.orElseThrow(() -> new NotValidOrderException("Book not found with ISBN: " + line.getBookId()));
totalPrice += book.getPrice() * line.getQuantity();
}
return totalPrice;
}
public UUID finalizeOrder() throws NotValidOrderException, UserNotFoundException, BookNotFoundException, IllegalBookStockException, IllegalCustomerPointException {
// Validation des données d'entrée
OrderInfo completeInfo = validateAndBuildOrderInfo();
// Récupération du client
Customer customer = customerRepository.findById(completeInfo.getCustomerId())
.orElseThrow(() -> new UserNotFoundException("Client introuvable"));
// Traitement des livres et calcul du prix
double totalPrice = processOrderLines(completeInfo.getOrderLines());
// Gestion du paiement
handlePayment(completeInfo, customer, totalPrice);
// Création et sauvegarde de la commande
UUID orderId = createAndSaveOrder(completeInfo, totalPrice);
// Nettoyage des données temporaires
resetTempData();
return orderId;
}
private OrderInfo validateAndBuildOrderInfo() throws NotValidOrderException, BookNotFoundException {
if (tempOrderInfo == null) throw new NotValidOrderException("Order info missing");
OrderInfo completeInfo = OrderInfo.builder()
.customerId(tempOrderInfo.getCustomerId())
.paymentMethod(tempOrderInfo.getPaymentMethod())
.orderLines(tempOrderLines)
.address(tempAddress)
.build();
// Validation centralisée
OrderValidator.validate(completeInfo, bookRepository, customerRepository);
return completeInfo;
}
private double processOrderLines(List<OrderLineDTO> orderLines) throws BookNotFoundException, IllegalBookStockException {
double totalPrice = 0.0;
for (OrderLineDTO line : orderLines) {
Book book = getBookOrThrow(line.getBookId());
updateBookStock(book, line.getQuantity());
totalPrice += calculateLinePrice(book, line.getQuantity());
}
return totalPrice;
}
private Book getBookOrThrow(String bookId) throws BookNotFoundException {
return bookRepository.findByISBN(bookId)
.orElseThrow(() -> new BookNotFoundException("Livre non trouvé: " + bookId));
}
private void updateBookStock(Book book, int quantity) throws IllegalBookStockException {
book.removeStock(quantity);
bookRepository.save(book);
}
private double calculateLinePrice(Book book, int quantity) {
return book.getPrice() * quantity;
}
private void handlePayment(OrderInfo orderInfo, Customer customer, double totalPrice) throws IllegalCustomerPointException {
if (isLoyaltyPointsPayment(orderInfo)) {
deductLoyaltyPoints(customer, totalPrice);
}
}
private boolean isLoyaltyPointsPayment(OrderInfo orderInfo) {
return "LOYALTY_POINTS".equalsIgnoreCase(orderInfo.getPaymentMethod());
}
private void deductLoyaltyPoints(Customer customer, double totalPrice) throws IllegalCustomerPointException {
int pointsToDeduct = (int) Math.round(totalPrice);
customer.removeLoyaltyPoints(pointsToDeduct);
customerRepository.save(customer);
}
private UUID createAndSaveOrder(OrderInfo orderInfo, double totalPrice) throws NotValidOrderException {
Order order = OrderConverter.toDomain(orderInfo);
order.setRandomUUID();
order.setAddress(tempAddress);
order.setOrderLines(tempOrderLines);
order.setTotalPrice(totalPrice);
order.setTotalPriceToPay(totalPrice);
orderRepository.save(order);
return order.getId();
}
private void resetTempData() {
tempOrderInfo = null;
tempOrderLines = null;
tempAddress = null;
}
public Optional<OrderDTO> findOrderById(UUID orderId) {
Optional<Order> order = orderRepository.findById(orderId);
return order.map(OrderConverter::toDTO);
}
public List<OrderDTO> findOrdersByCustomerId(UUID customerId) throws UserNotFoundException {
ensureCustomerExists(customerId);
List<Order> orders = orderRepository.findByCustomerId(customerId);
return orders.stream().map(OrderConverter::toDTO).collect(Collectors.toList());
}
private void ensureCustomerExists(UUID customerId) throws UserNotFoundException {
if (!customerRepository.findById(customerId).isPresent()) {
throw new UserNotFoundException("Customer not found");
}
}
public UUID registerOrder(OrderInfo orderInfo) throws NotValidOrderException, UserNotFoundException, BookNotFoundException {
OrderValidator.validate(orderInfo, bookRepository, customerRepository);
double total = computeTotalPrice(orderInfo.getOrderLines());
Order order = OrderConverter.toDomain(orderInfo);
order.setTotalPrice(total);
order.setTotalPriceToPay(total);
order.setRandomUUID();
orderRepository.save(order);
return order.getId();
}
}

View File

@@ -0,0 +1,135 @@
package fr.iut_fbleau.but3.dev62.mylibrary.order.validator;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.order.exception.NotValidOrderException;
import fr.iut_fbleau.but3.dev62.mylibrary.order.OrderLineDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.order.AddressDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.repository.CustomerRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
import fr.iut_fbleau.but3.dev62.mylibrary.order.exception.UserNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
import lombok.SneakyThrows;
import java.util.List;
public class OrderValidator {
public static final String CUSTOMER_ID_CANNOT_BE_NULL = "Customer ID cannot be null";
public static final String BOOK_LIST_CANNOT_BE_EMPTY = "Book list cannot be empty";
public static final String QUANTITY_MUST_BE_POSITIVE = "Quantity must be positive";
public static final String ADDRESS_FIELDS_ARE_REQUIRED = "Address fields are required";
public static final String PAYMENT_METHOD_IS_NOT_VALID = "Payment method is not valid";
private OrderValidator() {
}
public static void validate(OrderInfo orderInfo, BookRepository bookRepository, CustomerRepository customerRepository)
throws NotValidOrderException, UserNotFoundException, BookNotFoundException {
validateCustomerId(orderInfo);
Customer customer = validateCustomerExistence(orderInfo, customerRepository);
double totalPrice = validateBooksAndStock(orderInfo, bookRepository);
validateOrderLines(orderInfo);
validateAddress(orderInfo);
validatePaymentMethod(orderInfo);
validateLoyaltyPoints(orderInfo, customer, totalPrice);
}
private static Customer validateCustomerExistence(OrderInfo orderInfo, CustomerRepository customerRepository)
throws UserNotFoundException {
Customer customer = customerRepository.findById(orderInfo.getCustomerId()).orElse(null);
if (customer == null) {
throw new UserNotFoundException("Customer not found");
}
return customer;
}
private static double validateBooksAndStock(OrderInfo orderInfo, BookRepository bookRepository)
throws BookNotFoundException, NotValidOrderException {
double totalPrice = 0.0;
for (OrderLineDTO line : orderInfo.getOrderLines()) {
Book book = getBookOrThrow(line, bookRepository);
validateQuantityPositive(line);
validateStockSufficient(book, line);
totalPrice += book.getPrice() * line.getQuantity();
}
return totalPrice;
}
private static Book getBookOrThrow(OrderLineDTO line, BookRepository bookRepository) throws BookNotFoundException {
Book book = bookRepository.findByISBN(line.getBookId()).orElse(null);
if (book == null) {
throw new BookNotFoundException(line.getBookId());
}
return book;
}
private static void validateQuantityPositive(OrderLineDTO line) throws NotValidOrderException {
if (line.getQuantity() <= 0) {
throw new NotValidOrderException(QUANTITY_MUST_BE_POSITIVE);
}
}
private static void validateStockSufficient(Book book, OrderLineDTO line) throws NotValidOrderException {
if (book.getInitialStock() < line.getQuantity()) {
throw new NotValidOrderException("Insufficient book stock");
}
}
private static void validateLoyaltyPoints(OrderInfo orderInfo, Customer customer, double totalPrice)
throws NotValidOrderException {
if ("LOYALTY_POINTS".equalsIgnoreCase(orderInfo.getPaymentMethod())) {
int pointsToDeduct = (int) Math.round(totalPrice);
if (customer.getLoyaltyPoints() < pointsToDeduct) {
throw new NotValidOrderException("Not enough loyalty points");
}
}
}
private static void validateCustomerId(OrderInfo orderInfo) throws NotValidOrderException {
if (orderInfo.getCustomerId() == null) {
throw new NotValidOrderException(CUSTOMER_ID_CANNOT_BE_NULL);
}
}
private static void validateOrderLines(OrderInfo orderInfo) throws NotValidOrderException {
List<OrderLineDTO> lines = orderInfo.getOrderLines();
if (lines == null || lines.isEmpty()) {
throw new NotValidOrderException(BOOK_LIST_CANNOT_BE_EMPTY);
}
for (OrderLineDTO line : lines) {
validateOrderLine(line);
}
}
private static void validateOrderLine(OrderLineDTO line) throws NotValidOrderException {
validateQuantityPositive(line);
}
private static void validateAddress(OrderInfo orderInfo) throws NotValidOrderException {
AddressDTO address = orderInfo.getAddress();
if (address == null) {
throw new NotValidOrderException(ADDRESS_FIELDS_ARE_REQUIRED);
}
validateAddressFields(address);
}
private static void validateAddressFields(AddressDTO address) throws NotValidOrderException {
if (isBlank(address.getStreet()) || isBlank(address.getCity()) || isBlank(address.getPostalCode()) || isBlank(address.getCountry())) {
throw new NotValidOrderException(ADDRESS_FIELDS_ARE_REQUIRED);
}
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
private static void validatePaymentMethod(OrderInfo orderInfo) throws NotValidOrderException {
String method = orderInfo.getPaymentMethod();
if (method == null || method.isBlank() || !(method.equals("CREDIT_CARD") || method.equals("LOYALTY_POINTS"))) {
throw new NotValidOrderException(PAYMENT_METHOD_IS_NOT_VALID);
}
}
}

View File

@@ -0,0 +1,18 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import java.util.UUID;
@Builder
@Getter
@AllArgsConstructor
public class ReviewDto {
private final UUID reviewId;
private final String bookId; // Changed from long to String
private final String customerName;
private final String comment;
private final int rating;
}

View File

@@ -0,0 +1,15 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
@AllArgsConstructor
public class ReviewInfo {
private final String customerId;
private final String isbn; // Changed from long to String
private final int rating;
private final String comment;
}

View File

@@ -0,0 +1,28 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.converter;
import fr.iut_fbleau.but3.dev62.mylibrary.review.ReviewDto;
import fr.iut_fbleau.but3.dev62.mylibrary.review.ReviewInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.review.entity.Review;
import java.util.UUID;
public class ReviewConverter {
public static ReviewDto toDto(Review review, UUID reviewId, String customerName) {
return ReviewDto.builder()
.reviewId(reviewId)
.bookId(review.getIsbn()) // Changed from long to String
.customerName(customerName)
.comment(review.getComment())
.rating(review.getRating())
.build();
}
public static Review toDomain(ReviewInfo info) {
return Review.builder()
.customerId(UUID.fromString(info.getCustomerId()))
.isbn(info.getIsbn()) // Changed from long to String
.rating(info.getRating())
.comment(info.getComment())
.build();
}
}

View File

@@ -0,0 +1,20 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.UUID;
@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Review {
private UUID customerId;
private String isbn; // Changed from long to String
private int rating;
private String comment;
}

View File

@@ -0,0 +1,8 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.exception;
public class InvalidReviewRatingException extends RuntimeException {
public InvalidReviewRatingException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.exception;
public class NotValidReviewException extends Exception {
public NotValidReviewException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,8 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.exception;
public class ReviewAlreadyExistsException extends RuntimeException {
public ReviewAlreadyExistsException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,8 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.exception;
public class ReviewNotFoundException extends RuntimeException {
public ReviewNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,43 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.repository;
import fr.iut_fbleau.but3.dev62.mylibrary.review.entity.Review;
import java.util.*;
import java.util.stream.Collectors;
public class ReviewRepository {
private final List<Review> reviews = new ArrayList<>();
public void save(Review review) {
reviews.add(review);
}
public List<Review> findAll() {
return new ArrayList<>(reviews);
}
public List<Review> findByIsbn(String isbn) { // Changed from long to String
return reviews.stream().filter(r -> r.getIsbn().equals(isbn)).collect(Collectors.toList());
}
public List<Review> findByCustomerId(UUID customerId) {
return reviews.stream().filter(r -> r.getCustomerId().equals(customerId)).collect(Collectors.toList());
}
public boolean existsByCustomerIdAndIsbn(UUID customerId, String isbn) { // Changed from long to String
return reviews.stream().anyMatch(r -> r.getCustomerId().equals(customerId) && r.getIsbn().equals(isbn));
}
public void deleteByCustomerIdAndIsbn(UUID customerId, String isbn) { // Changed from long to String
reviews.removeIf(r -> r.getCustomerId().equals(customerId) && r.getIsbn().equals(isbn));
}
public void update(Review review) {
deleteByCustomerIdAndIsbn(review.getCustomerId(), review.getIsbn());
save(review);
}
public void deleteAll() {
reviews.clear();
}
}

View File

@@ -0,0 +1,73 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.usecase;
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.repository.CustomerRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.review.entity.Review;
import fr.iut_fbleau.but3.dev62.mylibrary.review.exception.InvalidReviewRatingException;
import fr.iut_fbleau.but3.dev62.mylibrary.review.exception.ReviewAlreadyExistsException;
import fr.iut_fbleau.but3.dev62.mylibrary.review.exception.ReviewNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.CustomerNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.review.repository.ReviewRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.review.validator.ReviewValidator;
import java.util.List;
import java.util.UUID;
public class ReviewUseCase {
private final ReviewRepository reviewRepository;
private final BookRepository bookRepository;
private final CustomerRepository customerRepository;
public ReviewUseCase(ReviewRepository reviewRepository, BookRepository bookRepository, CustomerRepository customerRepository) {
this.reviewRepository = reviewRepository;
this.bookRepository = bookRepository;
this.customerRepository = customerRepository;
}
public void submitReview(Review review) throws CustomerNotFoundException, BookNotFoundException {
ReviewValidator.validate(review);
System.out.println(bookRepository.existsByISBN(review.getIsbn()));
System.out.println(customerRepository.existsById(review.getCustomerId()));
System.out.println(customerRepository.findById(review.getCustomerId()));
System.out.println(reviewRepository.existsByCustomerIdAndIsbn(review.getCustomerId(), review.getIsbn()));
if (!bookRepository.existsByISBN(review.getIsbn())) {
throw new BookNotFoundException(review.getIsbn());
}
if (!customerRepository.existsById(review.getCustomerId())) {
throw new CustomerNotFoundException(review.getCustomerId());
}
if (reviewRepository.existsByCustomerIdAndIsbn(review.getCustomerId(), review.getIsbn())) {
throw new ReviewAlreadyExistsException("Review already exists for this customer and book.");
}
reviewRepository.save(review);
}
public List<Review> getReviewsByBook(String isbn) { // Changed from long to String
return reviewRepository.findByIsbn(isbn);
}
public List<Review> getReviewsByCustomer(UUID customerId) {
return reviewRepository.findByCustomerId(customerId);
}
public void updateReview(Review review) {
ReviewValidator.validate(review);
if (!reviewRepository.existsByCustomerIdAndIsbn(review.getCustomerId(), review.getIsbn())) { // Changed from long to String
throw new ReviewNotFoundException("Review not found for this customer and book.");
}
reviewRepository.update(review);
}
public void deleteReview(String isbn, UUID customerId) { // Changed from long to String
if (!reviewRepository.existsByCustomerIdAndIsbn(customerId, isbn)) { // Changed from long to String
throw new ReviewNotFoundException("Review not found for this customer and book.");
}
reviewRepository.deleteByCustomerIdAndIsbn(customerId, isbn);
}
}

View File

@@ -0,0 +1,46 @@
package fr.iut_fbleau.but3.dev62.mylibrary.review.validator;
import fr.iut_fbleau.but3.dev62.mylibrary.review.entity.Review;
import fr.iut_fbleau.but3.dev62.mylibrary.review.exception.InvalidReviewRatingException;
public class ReviewValidator {
public static final String ISBN_IS_NOT_VALID = "ISBN must be a valid 13-digit string";
public static void validate(Review review) {
validateReviewNotNull(review);
validateRating(review);
validateComment(review);
validateCustomerId(review);
validateBookIsbn(review);
}
private static void validateReviewNotNull(Review review) throws IllegalArgumentException {
if (review == null) {
throw new IllegalArgumentException("Review cannot be null");
}
}
private static void validateRating(Review review) throws InvalidReviewRatingException {
if (review.getRating() < 1 || review.getRating() > 5) {
throw new InvalidReviewRatingException("Rating must be between 1 and 5");
}
}
private static void validateComment(Review review) throws IllegalArgumentException {
if (review.getComment() == null || review.getComment().trim().isEmpty()) {
throw new IllegalArgumentException("Comment cannot be empty");
}
}
private static void validateCustomerId(Review review) throws IllegalArgumentException {
if (review.getCustomerId() == null) {
throw new IllegalArgumentException("Customer ID cannot be null");
}
}
private static void validateBookIsbn(Review review) throws IllegalArgumentException {
if (review.getIsbn() == null || !review.getIsbn().matches("\\d{13}")) {
throw new IllegalArgumentException(ISBN_IS_NOT_VALID);
}
}
}

View File

@@ -0,0 +1,15 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription;
import lombok.Builder;
import lombok.Getter;
import java.util.UUID;
@Builder
@Getter
public class SubscriptionDTO {
private final UUID id;
private final UUID customerId;
private final Integer duration;
private final String paymentMethod;
private final String debutDate;
}

View File

@@ -0,0 +1,7 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription;
import java.util.UUID;
public record SubscriptionInfo(UUID customerId, Integer duration, String paymentMethod) {
}

View File

@@ -0,0 +1,31 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription.converter;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.SubscriptionDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.SubscriptionInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.entity.Subscription;
public final class SubscriptionConverter {
private SubscriptionConverter() {
}
public static Subscription toDomain(SubscriptionInfo newSubscription) {
return Subscription.builder()
.customerId(newSubscription.customerId())
.duration(newSubscription.duration())
.paymentMethod(newSubscription.paymentMethod())
.build();
}
public static SubscriptionDTO toDTO(Subscription subscription) {
return SubscriptionDTO.builder()
.id(subscription.getId())
.customerId(subscription.getCustomerId())
.duration(subscription.getDuration())
.paymentMethod(subscription.getPaymentMethod())
.debutDate(subscription.getDebutDate())
.build();
}
}

View File

@@ -0,0 +1,24 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription.entity;
import java.util.UUID;
import lombok.Builder;
import lombok.Getter;
import java.time.LocalDate;
@Builder
@Getter
public class Subscription {
private UUID id;
private UUID customerId;
private Integer duration;
private String paymentMethod;
private String debutDate;
public void setRandomUUID() {
this.id = UUID.randomUUID();
}
public void setDebutDate(String debutDate) {
this.debutDate = LocalDate.now().toString();
}
}

View File

@@ -0,0 +1,8 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription.exception;
public class NotValidSubscriptionException extends Exception {
public NotValidSubscriptionException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,13 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription.exception;
import java.text.MessageFormat;
import java.util.UUID;
public class SubscriptionNotFoundException extends Exception {
public static final String THE_SUBSCRIPTION_WITH_ID_DOES_NOT_EXIST_MESSAGE = "The subscription with id {0} does not exist";
public SubscriptionNotFoundException(UUID uuid) {
super(MessageFormat.format(THE_SUBSCRIPTION_WITH_ID_DOES_NOT_EXIST_MESSAGE, uuid));
}
}

View File

@@ -0,0 +1,42 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription.repository;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.entity.Subscription;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import lombok.NoArgsConstructor;
public class SubscriptionRepository {
private final List<Subscription> subscriptions = new ArrayList<>();
public List<Subscription> findAll() {
return subscriptions;
}
public Subscription save(Subscription newSubscription) {
Optional<Subscription> optionalSubscriptionWithSameId = this.findByCustomerId(newSubscription.getCustomerId());
optionalSubscriptionWithSameId.ifPresentOrElse(subscriptions::remove, newSubscription::setRandomUUID);
this.subscriptions.add(newSubscription);
return newSubscription;
}
public Optional<Subscription> findByCustomerId(UUID uuid) {
return this.subscriptions.stream()
.filter(subscription -> subscription.getCustomerId().equals(uuid))
.findFirst();
}
public Optional<Subscription> findById(UUID id) {
return this.subscriptions.stream()
.filter(subscription -> subscription.getId().equals(id))
.findFirst();
}
public boolean existsById(UUID uuid) {
return this.subscriptions.stream()
.anyMatch(subscription -> subscription.getId().equals(uuid));
}
}

View File

@@ -0,0 +1,45 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription.usecase;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.SubscriptionDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.SubscriptionInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.converter.SubscriptionConverter;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.entity.Subscription;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.exception.SubscriptionNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.exception.NotValidSubscriptionException;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.repository.SubscriptionRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.validator.SubscriptionValidator;
import java.util.Optional;
import java.util.UUID;
public class SubscriptionUseCase {
private final SubscriptionRepository subscriptionRepository;
public SubscriptionUseCase(SubscriptionRepository subscriptionRepository) {
this.subscriptionRepository = subscriptionRepository;
}
public UUID registerSubscription(SubscriptionInfo newSubscription) throws NotValidSubscriptionException {
SubscriptionValidator.validate(newSubscription);
Subscription subscriptionToRegister = SubscriptionConverter.toDomain(newSubscription);
Subscription subscriptionToRegistered = subscriptionRepository.save(subscriptionToRegister);
if (subscriptionToRegistered.getDuration() <= 0) {
throw new NotValidSubscriptionException("Duration must be positive");
}
return subscriptionToRegistered.getId();
}
public Optional<SubscriptionDTO> findSubscriptionByCustomerId(UUID customerId) {
Optional<Subscription> optionalSubscription = subscriptionRepository.findByCustomerId(customerId);
return optionalSubscription.map(SubscriptionConverter::toDTO);
}
private boolean getSubscriptionIfDoesNotExistThrowSubscriptionNotFoundException(UUID uuid)
throws SubscriptionNotFoundException {
if (subscriptionRepository.existsById(uuid)) {
throw new SubscriptionNotFoundException(uuid);
}
return subscriptionRepository.existsById(uuid);
}
}

View File

@@ -0,0 +1,44 @@
package fr.iut_fbleau.but3.dev62.mylibrary.subscription.validator;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.NotValidCustomerException;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.SubscriptionDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.SubscriptionInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.subscription.exception.NotValidSubscriptionException;
public class SubscriptionValidator {
public static final String CUSTOMER_ID_CANNOT_BE_NULL = "Customer ID cannot be null";
public static final String DURATION_CANNOT_BE_NULL = "Duration is not valid";
public static final String PAYMENT_METHOD_CANNOT_BE_BLANK = "Payment Method cannot be blank";
private SubscriptionValidator() {
}
public static void validate(SubscriptionInfo newSubscription) throws NotValidSubscriptionException {
validateCustomerId(newSubscription);
validateDuration(newSubscription);
validatePaymentMethod(newSubscription);
}
private static void validateCustomerId(SubscriptionInfo newSubscription) throws NotValidSubscriptionException {
if (newSubscription.customerId() == null) {
throw new NotValidSubscriptionException(CUSTOMER_ID_CANNOT_BE_NULL);
}
}
private static void validateDuration(SubscriptionInfo newSubscription) throws NotValidSubscriptionException {
if (newSubscription.duration() == null) {
throw new NotValidSubscriptionException(DURATION_CANNOT_BE_NULL);
}
}
private static void validatePaymentMethod(SubscriptionInfo newSubscription) throws NotValidSubscriptionException {
if (newSubscription.paymentMethod().isBlank()) {
throw new NotValidSubscriptionException(PAYMENT_METHOD_CANNOT_BE_BLANK);
}
}
}

View File

@@ -0,0 +1,138 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.converter;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.converter.BookConverter;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
@DisplayName("BookConverter Unit Tests")
public class BookConverterTest {
@Nested
@DisplayName("toDomain() method tests")
class ToDomainTests {
@Test
@DisplayName("Should convert BookInfo to Book domain object")
void shouldConvertBookInfoToDomain() {
// Given
ArrayList<String> categories = new ArrayList<>(); categories.add("Categorie1"); categories.add("Categorie2");
BookInfo bookInfo = new BookInfo("1234567891234", "Livre", "john doe","editeur", Date.from(Instant.now()),5.99,15,categories,"description","langue");
// When
Book result = BookConverter.toDomain(bookInfo);
// Then
assertNotNull(result);
assertEquals(bookInfo.isbn(), result.getIsbn());
assertEquals(bookInfo.title(), result.getTitle());
assertEquals(bookInfo.author(), result.getAuthor());
assertEquals(bookInfo.publisher(), result.getPublisher());
assertEquals(bookInfo.date(), result.getDate());
assertEquals(bookInfo.price(), result.getPrice());
assertEquals(bookInfo.initialStock(), result.getInitialStock());
assertEquals(bookInfo.categories(), result.getCategories());
assertEquals(bookInfo.description(), result.getDescription());
assertEquals(bookInfo.language(), result.getLanguage());
}
}
@Nested
@DisplayName("toDTO() method tests")
class ToDTOTests {
@Test
@DisplayName("Should convert Book domain object to BookDTO with all fields mapped correctly")
void shouldConvertBookToDTO() {
ArrayList<String> categories = new ArrayList<>(); categories.add("Categorie1"); categories.add("Categorie2");
Book book = Book.builder()
.isbn("1234567890123")
.title("Livre 1")
.author("John Updated")
.publisher("Editeur")
.date(Date.from(Instant.now()))
.price(4.99)
.initialStock(42)
.categories(categories)
.description("Description")
.language("Francais")
.build();
BookDTO result = BookConverter.toDTO(book);
assertNotNull(result);
assertEquals(book.getIsbn(), result.getIsbn());
assertEquals(book.getTitle(), result.getTitle());
assertEquals(book.getAuthor(), result.getAuthor());
assertEquals(book.getPublisher(), result.getPublisher());
assertEquals(book.getDate(), result.getDate());
assertEquals(book.getPrice(), result.getPrice());
assertEquals(book.getInitialStock(), result.getInitialStock());
assertEquals(book.getCategories(), result.getCategories());
assertEquals(book.getDescription(), result.getDescription());
assertEquals(book.getLanguage(), result.getLanguage());
}
}
@Test
@DisplayName("Should handle null values properly when converting between objects")
void shouldHandleNullValuesGracefully() {
Book book = Book.builder()
.isbn("1234567890123")
.title("Null")
.author("Null")
.publisher("Null")
.date(null)
.price(4.99)
.initialStock(42)
.categories(null)
.description(null)
.language(null)
.build();
BookDTO result = BookConverter.toDTO(book);
assertNotNull(result);
assertEquals(book.getIsbn(), result.getIsbn());
assertEquals(book.getTitle(), result.getTitle());
assertEquals(book.getAuthor(), result.getAuthor());
assertEquals(book.getPublisher(), result.getPublisher());
assertNull(result.getDate());
assertEquals(book.getPrice(), result.getPrice());
assertEquals(book.getInitialStock(), result.getInitialStock());
assertNull(result.getCategories());
assertNull(result.getDescription());
assertNull(result.getLanguage());
}
@Test
@DisplayName("Should preserve empty string values during conversion")
void shouldPreserveEmptyStrings() {
BookInfo bookInfo = new BookInfo("1234567890123", "e", "e","e",null,1.2,5,null,"","");
Book domainResult = BookConverter.toDomain(bookInfo);
BookDTO result = BookConverter.toDTO(domainResult);
assertEquals(bookInfo.isbn(), result.getIsbn()); //ISBN ne peut pas etre vide
assertEquals(bookInfo.title(), result.getTitle()); // Le titre ne peut pas etre vide
assertEquals(bookInfo.author(), result.getAuthor()); // L'auteur ne peut pas etre vide
assertEquals(bookInfo.publisher(), result.getPublisher()); // L'editeur ne peut pas etre vide
assertEquals(null, result.getDate());
assertEquals(bookInfo.price(), result.getPrice());
assertEquals(bookInfo.initialStock(), result.getInitialStock());
assertEquals(null, result.getCategories());
assertEquals("", result.getDescription());
assertEquals("", result.getLanguage());
}
}

Some files were not shown because too many files have changed in this diff Show More