Skip to content

Commit

Permalink
Remove unused Dockerfile, docker-compose.yml, and readme
Browse files Browse the repository at this point in the history
Uppdate files with comments for clarity
  • Loading branch information
amine20akka committed Dec 29, 2024
1 parent 068e497 commit 783bde2
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 117 deletions.
11 changes: 0 additions & 11 deletions cart/Dockerfile

This file was deleted.

27 changes: 0 additions & 27 deletions cart/docker-compose.yml

This file was deleted.

1 change: 0 additions & 1 deletion cart/readme

This file was deleted.

40 changes: 21 additions & 19 deletions cart/src/main/java/org/soa/api/CartResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,18 +80,18 @@ public Response getItems(@PathParam("userId") UUID userId) {
}
}

// Ajouter un item au panier d'un utilisateur
@POST
@Path("/{userId}/add-item/{productId}")
public Response addItemFromCatalog(
@PathParam("userId") UUID userId,
@PathParam("productId") UUID productId,
@QueryParam("quantity") @DefaultValue("1") int quantity) {
@PathParam("userId") UUID userId,
@PathParam("productId") UUID productId,
@QueryParam("quantity") @DefaultValue("1") int quantity) {

Item newItem = cartService.addItemFromCatalog(userId,productId, quantity);
Item newItem = cartService.addItemFromCatalog(userId, productId, quantity);
return Response.status(Status.CREATED).entity(newItem).build();
}


// Mettre à jour un item dans le panier d'un utilisateur
@PUT
@Path("/{userId}/update-item")
Expand Down Expand Up @@ -129,6 +129,7 @@ public Response removeItem(@PathParam("userId") UUID userId, @PathParam("product
}
}

// Valider le panier d'un utilisateur
@POST
@Path("/{userId}/validate")
public Response validateCart(@PathParam("userId") UUID userId) {
Expand All @@ -140,22 +141,23 @@ public Response validateCart(@PathParam("userId") UUID userId) {
@DELETE
@Path("/{userId}/clear")
public Response clearCart(@PathParam("userId") UUID userId) {
try {
logger.info("Clearing cart for User ID: " + userId);

cartService.clearCart(userId);
logger.info("Cart cleared successfully for User ID: " + userId);

return Response.status(Status.NO_CONTENT).build();
} catch (IllegalArgumentException e) {
logger.warn("Invalid input: " + e.getMessage());
return Response.status(Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (Exception e) {
logger.error("Unexpected error occurred while clearing cart: " + e.getMessage(), e);
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
try {
logger.info("Clearing cart for User ID: " + userId);

cartService.clearCart(userId);
logger.info("Cart cleared successfully for User ID: " + userId);

return Response.status(Status.NO_CONTENT).build();
} catch (IllegalArgumentException e) {
logger.warn("Invalid input: " + e.getMessage());
return Response.status(Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (Exception e) {
logger.error("Unexpected error occurred while clearing cart: " + e.getMessage(), e);
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}

// Récupérer les détails d'un item
@GET
@Path("/item/{itemId}")
public ItemDTO getItemDetails(@PathParam("itemId") UUID itemId) {
Expand Down
5 changes: 3 additions & 2 deletions cart/src/main/java/org/soa/api/CatalogueClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
import org.soa.dto.ItemDTO;
import java.util.UUID;

@RegisterRestClient(configKey = "catalog-api")
@Path("/products")
@RegisterRestClient(configKey = "catalog-api") // Correspond à la clé de configuration
@Path("/products") // Correspond à l'URI de base
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface CatalogueClient {

// Récupérer les détails d'un item
@GET
@Path("/{id}")
ItemDTO fetchItemDetails(@PathParam("id") UUID id);
Expand Down
2 changes: 1 addition & 1 deletion cart/src/main/java/org/soa/config/RedisConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class RedisConfig {
@ApplicationScoped
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer().setAddress("redis://localhost:6379");
config.useSingleServer().setAddress("redis://localhost:6379"); // Redis server address
return Redisson.create(config);
}
}
4 changes: 2 additions & 2 deletions cart/src/main/java/org/soa/dto/ItemDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ public class ItemDTO {

private UUID itemId; // Identifiant de l'item
private String name; // Nom de l'item
private int quantity;
private double price; // Quantité de l'item
private int quantity; // Quantité de l'item
private double price; // Prix de l'item

// Constructeur sans paramètres
public ItemDTO() {
Expand Down
134 changes: 85 additions & 49 deletions cart/src/main/java/org/soa/service/CartService.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,57 @@

@ApplicationScoped
public class CartService {


public ItemDTO getItemDetails(UUID itemId) {
return catalogueClient.fetchItemDetails(itemId);
}

@Inject
RedissonClient redissonClient;

@Inject
@RestClient
CatalogueClient catalogueClient;

@Inject
CartPublisher cartPublisher;

private static final Logger logger = Logger.getLogger(CartService.class);

/**
* Retrieves the map of carts from the Redis cache.
*
* @return RMapCache<UUID, Cart> representing the carts.
*/
private RMapCache<UUID, Cart> getCartsMap() {
return redissonClient.getMapCache("carts");
}

// Créer un nouveau panier
/**
* Fetches item details from the Catalogue service.
*
* @param itemId UUID of the item to fetch details for.
* @return ItemDTO containing the item details.
*/
public ItemDTO getItemDetails(UUID itemId) {
return catalogueClient.fetchItemDetails(itemId);
}

/**
* Creates a new cart for a user.
*
* @param userId UUID of the user.
* @return Cart object representing the newly created cart.
*/
public Cart createCart(UUID userId) {
try {
logger.info("Creating cart for userId: " + userId);

// Utiliser RMapCacheCache pour permettre la gestion du TTL
RMapCache<UUID, Cart> carts = redissonClient.getMapCache("carts");

if (carts.containsKey(userId)) {
logger.error("Cart already exists for userId: " + userId);
throw new IllegalStateException("Cart already exists for userId: " + userId);
}

// Créer un nouveau panier
Cart cart = new Cart(userId);

// Ajouter le panier avec une durée de vie de 24 heures
carts.put(userId, cart, 24, TimeUnit.HOURS);
carts.put(userId, cart, 24, TimeUnit.HOURS); // Cache the cart for 24 hours

logger.info("Cart created successfully for userId: " + userId);
return cart;
Expand All @@ -61,7 +79,12 @@ public Cart createCart(UUID userId) {
}
}

// Récupérer un panier par userId
/**
* Retrieves an existing cart by user ID.
*
* @param userId UUID of the user.
* @return Cart object if found.
*/
public Cart getCart(UUID userId) {
try {
logger.info("Fetching cart for userId: " + userId);
Expand All @@ -79,33 +102,37 @@ public Cart getCart(UUID userId) {
throw new RuntimeException("An unexpected error occurred while fetching the cart.", e);
}
}

@Inject
@RestClient
CatalogueClient catalogueClient;

/**
* Adds an item to the user's cart by fetching item details from the catalogue.
*
* @param userId UUID of the user.
* @param productId UUID of the product to add.
* @param quantity Quantity of the product to add.
* @return Item object representing the added item.
*/
public Item addItemFromCatalog(UUID userId, UUID productId, int quantity) {
// Récupérer les informations du produit via l'API Catalogue
ItemDTO product = catalogueClient.fetchItemDetails(productId);

if (product == null) {
throw new IllegalArgumentException("Produit non trouvé pour l'ID : " + productId);
}

RMapCache<UUID, Cart> carts = getCartsMap();
Cart cart = carts.get(userId);

Item newItem = new Item(productId, quantity, product.getPrice(), product.getName());

// Ajoutez cet item au panier existant
cart.getItems().put(newItem.getItemId(), newItem);
carts.put(userId, cart);
return newItem;
}



// Mettre à jour un item dans le panier
/**
* Updates an item in the user's cart.
*
* @param userId UUID of the user.
* @param cartItem Item object with updated details.
*/
public void updateItem(UUID userId, Item cartItem) {
try {
logger.info("Updating item in cart for userId: " + userId);
Expand All @@ -131,7 +158,12 @@ public void updateItem(UUID userId, Item cartItem) {
}
}

// Supprimer un item du panier
/**
* Removes an item from the user's cart.
*
* @param userId UUID of the user.
* @param itemId UUID of the item to remove.
*/
public void removeItem(UUID userId, UUID itemId) {
try {
logger.info("Removing item from cart for userId: " + userId);
Expand All @@ -157,7 +189,12 @@ public void removeItem(UUID userId, UUID itemId) {
}
}

// Récupérer l'historique des items du panier
/**
* Retrieves all items from the user's cart.
*
* @param userId UUID of the user.
* @return List of Item objects in the cart.
*/
public List<Item> getCartItems(UUID userId) {
try {
logger.info("Fetching items from cart for userId: " + userId);
Expand All @@ -176,7 +213,11 @@ public List<Item> getCartItems(UUID userId) {
}
}

// Supprimer le panier
/**
* Deletes the user's cart.
*
* @param userId UUID of the user.
*/
public void deleteCart(UUID userId) {
try {
logger.info("Deleting cart for userId: " + userId);
Expand All @@ -195,24 +236,24 @@ public void deleteCart(UUID userId) {
}
}

// Vider le panier
/**
* Clears all items in the user's cart.
*
* @param userId UUID of the user.
*/
public void clearCart(UUID userId) {
try {
logger.info("Clearing cart for userId: " + userId);
RMapCache<UUID, Cart> carts = getCartsMap();

// Vérifier si le panier existe
if (!carts.containsKey(userId)) {
logger.error("Cart not found for userId: " + userId);
throw new IllegalArgumentException("Cart not found for userId: " + userId);
}

// Récupérer le panier
Cart cart = carts.get(userId);

// Vider le contenu du panier
cart.getItems().clear();
carts.put(userId, cart); // Mettre à jour la carte après nettoyage
carts.put(userId, cart);

logger.info("Cart cleared successfully for userId: " + userId);
} catch (Exception e) {
Expand All @@ -221,32 +262,27 @@ public void clearCart(UUID userId) {
}
}

@Inject
CartPublisher cartPublisher;

/**
* Validates and publishes the user's cart to the messaging broker.
*
* @param cartId UUID of the cart to validate.
*/
public void validateCart(UUID cartId) {
// Récupérer le panier à partir de son ID
Cart cart = getCart(cartId);
if (cart == null) {
throw new IllegalArgumentException("Cart not found with ID: " + cartId);
}

// Vérifier si le panier est vide

if (cart.getItems() == null || cart.getItems().isEmpty()) {
throw new IllegalArgumentException("Cannot validate an empty cart.");
}

// Convertir les items du panier en objets ItemDTO

List<ItemDTO> itemDTOs = cart.getItems().entrySet().stream()
.map(entry -> new ItemDTO(entry.getKey(), entry.getValue().getName(),
entry.getValue().getQuantity(), entry.getValue().getPrice()))
.toList();

// Publier le panier dans le broker
.map(entry -> new ItemDTO(entry.getKey(), entry.getValue().getName(),
entry.getValue().getQuantity(), entry.getValue().getPrice()))
.toList();

cartPublisher.publishCart(cartId, itemDTOs);

// Optionnel : journaliser l'action
logger.info("Cart with ID: " + cartId + " successfully published to the broker.");
}

}
Loading

0 comments on commit 783bde2

Please sign in to comment.