diff --git a/.gitignore b/.gitignore index 5eac309..773a43e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ +# Ignore Maven build output +/target/ +/logs/ + HELP.md target/ !.mvn/wrapper/maven-wrapper.jar @@ -30,4 +34,5 @@ build/ !**/src/test/**/build/ ### VS Code ### -.vscode/ \ No newline at end of file +.vscode/ + diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -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 diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..3f44e05 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..aa00ffa --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..712ab9d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..0e6e319 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..fd7dc73 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,59 @@ +version: '3.8' + +services: + + cart-service: + image: openjdk:25-ea-4-jdk-oraclelinux9 + container_name: cart-service + ports: + - "8081:8080" + environment: + SPRING_DATA_MONGODB_URI: mongodb://cart-db:27017/cartDB + SPRING_DATA_MONGODB_DATABASE: cartDB + depends_on: + - cart-db + volumes: + - ./target:/app + - ./logs:/logs + command: ["java", "-jar", "/app/cart-0.0.1-SNAPSHOT.jar"] + + cart-db: + image: mongo:8.0.9 + container_name: cart-db + environment: + MONGO_INITDB_DATABASE: cartDB + ports: + - "27018:27017" + volumes: + - cart-mongo-data:/data/db + + # Reuse Loki and Promtail from your existing setup + loki: + image: grafana/loki:latest + container_name: loki + ports: + - "3100:3100" + command: + - -config.file=/etc/loki/local-config.yaml + + promtail: + image: grafana/promtail:latest + container_name: promtail + volumes: + - ./promtail.yml:/etc/promtail/promtail-config.yaml + - ./logs:/logs + command: + - -config.file=/etc/promtail/promtail-config.yaml + depends_on: + - loki + + grafana: + image: grafana/grafana:latest + container_name: grafana + ports: + - "3000:3000" + depends_on: + - loki + +volumes: + cart-mongo-data: \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..337a47c --- /dev/null +++ b/pom.xml @@ -0,0 +1,179 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.4.5 + + + + com.podzilla + cart + 0.0.1-SNAPSHOT + cart + This is the cart service for Podzilla + + + 23 + + + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + + org.springframework.boot + spring-boot-starter-web + + + + + jakarta.validation + jakarta.validation-api + 3.0.2 + + + + + org.projectlombok + lombok + true + + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.8.5 + + + + + net.logstash.logback + logstash-logback-encoder + 7.4 + + + + + org.springframework.boot + spring-boot-devtools + runtime + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.junit.jupiter + junit-jupiter + 5.10.0 + test + + + + org.mockito + mockito-core + 5.5.0 + test + + + + org.mockito + mockito-junit-jupiter + 5.5.0 + test + + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + 4.9.3 + test + + + + org.springframework.security + spring-security-test + test + + + + + com.github.tomakehurst + wiremock-jre8 + 2.35.0 + test + + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + 4.9.3 + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.github.tomakehurst + wiremock-jre8 + 2.35.0 + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + diff --git a/promtail.yml b/promtail.yml new file mode 100644 index 0000000..1ede004 --- /dev/null +++ b/promtail.yml @@ -0,0 +1,18 @@ +server: + http_listen_port: 9080 + grpc_listen_port: 0 + +positions: + filename: /tmp/positions.yaml + +clients: + - url: http://loki:3100/loki/api/v1/push + +scrape_configs: + - job_name: cart-service + static_configs: + - targets: + - localhost + labels: + job: cart-service + __path__: ./logs/*.log \ No newline at end of file diff --git a/src/main/java/cart/CartApplication.java b/src/main/java/cart/CartApplication.java new file mode 100644 index 0000000..2ef8d6d --- /dev/null +++ b/src/main/java/cart/CartApplication.java @@ -0,0 +1,13 @@ +package cart; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; + +@SpringBootApplication +@EnableMongoRepositories(basePackages = "cart.repository") +public class CartApplication { + public static void main(final String[] args) { + SpringApplication.run(CartApplication.class, args); + } +} diff --git a/src/main/java/cart/config/AppConfig.java b/src/main/java/cart/config/AppConfig.java new file mode 100644 index 0000000..70500cc --- /dev/null +++ b/src/main/java/cart/config/AppConfig.java @@ -0,0 +1,15 @@ +package cart.config; + + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class AppConfig { + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/src/main/java/cart/controller/CartController.java b/src/main/java/cart/controller/CartController.java new file mode 100644 index 0000000..6260409 --- /dev/null +++ b/src/main/java/cart/controller/CartController.java @@ -0,0 +1,241 @@ +package cart.controller; + + + +import cart.model.Cart; +import cart.service.CartService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestBody; +import cart.model.CartItem; +import io.swagger.v3.oas.annotations.media.Content; + +@RestController +@RequestMapping("/api/carts") +@RequiredArgsConstructor +@Tag(name = "Cart Controller", description = "Handles cart" + + " operations like add, update," + + " remove items and manage cart") +@Slf4j +public class CartController { + + private final CartService cartService; + + @Operation(summary = "Create a new cart for a " + + "customer or return existing one") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Cart created or retrieved successfully"), + @ApiResponse(responseCode = "400", + description = "Invalid customer ID provided", + content = @Content), + @ApiResponse(responseCode = "500", + description = "Internal server error", + content = @Content) + }) + @PostMapping("/create/{customerId}") + public ResponseEntity createCart( + @PathVariable("customerId") final String customerId) { + log.debug("Entering createCart endpoint" + + " with customerId:", customerId); + Cart cart = cartService.createCart(customerId); + log.debug("Cart created or retrieved:", cart); + return ResponseEntity.ok(cart); + } + + @Operation(summary = "Get cart by customer ID") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Cart retrieved successfully"), + @ApiResponse(responseCode = "404", + description = "Cart not found for this customer") + }) + @GetMapping("/customer/{customerId}") + public ResponseEntity getCartByCustomerId( + @PathVariable("customerId") final String customerId) { + log.debug("Entering getCartByCustomerId" + + " endpoint with customerId:", + customerId); + Cart cart = cartService.getCartByCustomerId(customerId); + log.debug("Cart retrieved:", cart); + return ResponseEntity.ok(cart); + } + + @Operation(summary = "Delete cart by customer ID") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", + description = "Cart deleted successfully"), + @ApiResponse(responseCode = "404", + description = "Cart not found") + }) + @DeleteMapping("/customer/{customerId}") + public ResponseEntity deleteCart( + @PathVariable("customerId") final String customerId) { + log.debug("Entering deleteCart end" + + "point with customerId:", customerId); + cartService.deleteCartByCustomerId(customerId); + log.debug("Cart deleted for customerId:", + customerId); + + return ResponseEntity.noContent().build(); + } + + @Operation(summary = "Add an item to the cart" + + " or update its quantity if already exists") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Item added or updated successfully"), + @ApiResponse(responseCode = "400", + description = "Invalid item data provided"), + @ApiResponse(responseCode = "404", + description = "Cart not found for this customer") + }) + @PostMapping("/{customerId}/items") + public ResponseEntity addItemToCart( + @PathVariable("customerId") final String customerId, + @RequestBody final CartItem cartItem) { + log.debug("Entering addItemToCart" + + " endpoint with customerId: {}," + + " cartItem: {}", customerId, cartItem); + Cart updatedCart = cartService.addItemToCart(customerId, cartItem); + log.debug("Cart updated with new item: {}", updatedCart); + return ResponseEntity.ok(updatedCart); + } + + @Operation(summary = "Update quantity " + + "of an existing item in the cart") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Quantity updated successfully"), + @ApiResponse(responseCode = "400", + description = "Invalid quantity value"), + @ApiResponse(responseCode = "404", + description = "Cart or item not found") + }) + @PatchMapping("/{customerId}/items/{productId}") + public ResponseEntity updateItemQuantity( + @PathVariable("customerId") final String customerId, + @PathVariable("productId") final String productId, + @RequestParam final int quantity) { + log.debug("Entering updateItemQuantity" + + " endpoint with customerId:," + + " productId: {}, quantity: {}", + customerId, productId, quantity); + Cart updatedCart = cartService.updateItemQuantity( + customerId, productId, quantity); + log.debug("Cart updated with new quantity:", + updatedCart); + return ResponseEntity.ok(updatedCart); + } + + @Operation(summary = "Remove an item from the cart") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Item removed successfully"), + @ApiResponse(responseCode = "404", + description = "Cart or item not found") + }) + @DeleteMapping("/{customerId}/items/{productId}") + public ResponseEntity removeItemFromCart( + @PathVariable("customerId") final String customerId, + @PathVariable("productId") final String productId) { + log.debug("Entering removeItemFromCart" + + " endpoint with customerId:," + + " productId:", customerId, productId); + Cart updatedCart = cartService + .removeItemFromCart(customerId, productId); + log.debug("Cart updated after item removal:", + updatedCart); + return ResponseEntity.ok(updatedCart); + } + + @Operation(summary = "Clear all items from the cart") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", + description = "Cart cleared successfully"), + @ApiResponse(responseCode = "404", + description = "Cart not found") + }) + @DeleteMapping("/{customerId}/clear") + public ResponseEntity clearCart( + @PathVariable("customerId") final String customerId) { + log.debug("Entering clearCart" + + " endpoint with customerId:", customerId); + cartService.clearCart(customerId); + log.debug("Cart cleared for customerId:", customerId); + return ResponseEntity.noContent().build(); + } + + @Operation(summary = "Archive the cart (soft-delete)") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Cart successfully archived"), + @ApiResponse(responseCode = "404", + description = "Cart not found") + }) + @PatchMapping("/{customerId}/archive") + public ResponseEntity archiveCart( + @PathVariable("customerId") final String customerId) { + log.debug("Entering archiveCart" + + " endpoint with customerId:", customerId); + Cart archivedCart = cartService.archiveCart(customerId); + log.debug("Cart archived:", archivedCart); + return ResponseEntity.ok(archivedCart); + } + + @Operation(summary = "Unarchive a previously archived cart") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Cart successfully unarchived"), + @ApiResponse(responseCode = "404", + description = "Archived cart not found") + }) + @PatchMapping("/{customerId}/unarchive") + public ResponseEntity unarchiveCart( + @PathVariable("customerId") final String customerId) { + log.debug("Entering unarchiveCart" + + " endpoint with customerId:", customerId); + Cart activeCart = cartService.unarchiveCart(customerId); + log.debug("Cart unarchived:", activeCart); + return ResponseEntity.ok(activeCart); + } + + @Operation(summary = "Checkout cart by sending it to the Order Service") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", + description = "Cart checked out and sent to Order Service"), + @ApiResponse(responseCode = "404", + description = "Cart not found"), + @ApiResponse(responseCode = "500", + description = "Failed to communicate with Order Service") + }) + @PostMapping("/{customerId}/checkout") + public ResponseEntity checkoutCart( + @PathVariable("customerId") final String customerId) { + log.debug("Entering checkoutCart" + + " endpoint with customerId:", customerId); + try { + Cart updatedCart = cartService.checkoutCart(customerId); + log.debug("Cart checked out: {}", updatedCart); + return ResponseEntity.ok(updatedCart); + } catch (Exception ex) { + log.error("Error during checkout" + + " for customerId: {}", customerId, ex); + throw new IllegalCallerException("Error " + + "communicating with Order Service"); + } + } +} diff --git a/src/main/java/cart/exception/GlobalExceptionHandler.java b/src/main/java/cart/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..4b03133 --- /dev/null +++ b/src/main/java/cart/exception/GlobalExceptionHandler.java @@ -0,0 +1,24 @@ +package cart.exception; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.util.HashMap; +import java.util.Map; + +@ControllerAdvice +public class GlobalExceptionHandler + extends ResponseEntityExceptionHandler { + @ExceptionHandler(GlobalHandlerException.class) + public ResponseEntity> + handleGlobalHandlerException(final + GlobalHandlerException ex) { + Map errorResponse = new HashMap<>(); + errorResponse.put("status", ex.getStatus().value()); + errorResponse.put("error", ex.getStatus().getReasonPhrase()); + errorResponse.put("message", ex.getMessage()); + return new ResponseEntity<>(errorResponse, ex.getStatus()); + } +} diff --git a/src/main/java/cart/exception/GlobalHandlerException.java b/src/main/java/cart/exception/GlobalHandlerException.java new file mode 100644 index 0000000..d6b665b --- /dev/null +++ b/src/main/java/cart/exception/GlobalHandlerException.java @@ -0,0 +1,26 @@ +package cart.exception; + +import org.springframework.http.HttpStatus; + +public class GlobalHandlerException extends + RuntimeException { + + private final HttpStatus status; + + public GlobalHandlerException(final + HttpStatus status, final String message) { + super(message); + this.status = status; + } + + public GlobalHandlerException(final + HttpStatus status, final String message, + final Throwable cause) { + super(message, cause); + this.status = status; + } + + public HttpStatus getStatus() { + return status; + } +} diff --git a/src/main/java/cart/model/Cart.java b/src/main/java/cart/model/Cart.java new file mode 100644 index 0000000..6d93d92 --- /dev/null +++ b/src/main/java/cart/model/Cart.java @@ -0,0 +1,32 @@ +package cart.model; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; + +import java.util.ArrayList; +import java.util.List; + +@Document(collection = "carts") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Cart { + + @Id + @Field("_id") + private String id; + + @NotBlank + private String customerId; + + private List items = new ArrayList<>(); + + private boolean archived = false; + +} + diff --git a/src/main/java/cart/model/CartItem.java b/src/main/java/cart/model/CartItem.java new file mode 100644 index 0000000..1a147c3 --- /dev/null +++ b/src/main/java/cart/model/CartItem.java @@ -0,0 +1,18 @@ +package cart.model; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CartItem { + + @NotBlank + private String productId; + + private int quantity; + +} diff --git a/src/main/java/cart/model/OrderRequest.java b/src/main/java/cart/model/OrderRequest.java new file mode 100644 index 0000000..80b8bb2 --- /dev/null +++ b/src/main/java/cart/model/OrderRequest.java @@ -0,0 +1,21 @@ +package cart.model; + + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class OrderRequest { + + @NotBlank + private String customerId; + + private List items; + +} diff --git a/src/main/java/cart/repository/CartRepository.java b/src/main/java/cart/repository/CartRepository.java new file mode 100644 index 0000000..65d18fd --- /dev/null +++ b/src/main/java/cart/repository/CartRepository.java @@ -0,0 +1,15 @@ +package cart.repository; + +import cart.model.Cart; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface CartRepository extends MongoRepository { + Optional findByCustomerId(String customerId); + Optional findByCustomerIdAndArchived( + String customerId, boolean archived); + +} diff --git a/src/main/java/cart/service/AddItemCommand.java b/src/main/java/cart/service/AddItemCommand.java new file mode 100644 index 0000000..a0755c2 --- /dev/null +++ b/src/main/java/cart/service/AddItemCommand.java @@ -0,0 +1,66 @@ +package cart.service; + +import cart.model.Cart; +import cart.model.CartItem; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import java.util.Optional; + +@RequiredArgsConstructor +@Slf4j +public class AddItemCommand implements CartCommand { + + private final CartService cartService; + private final String customerId; + private final CartItem newItem; + + @Override + public Cart execute() { + log.debug("Executing AddItemCommand for customerId: {}, item: {}", customerId, newItem); + Cart cart = cartService.getCartByCustomerId(customerId); + + Optional existingItem = cart.getItems().stream() + .filter(i -> i.getProductId().equals(newItem.getProductId())) + .findFirst(); + + if (existingItem.isPresent()) { + log.debug("Item exists, updating quantity for productId: {}", newItem.getProductId()); + existingItem.get().setQuantity(existingItem.get().getQuantity() + newItem.getQuantity()); + } else { + log.debug("Adding new item to cart for productId: {}", newItem.getProductId()); + cart.getItems().add(newItem); + } + + Cart updatedCart = cartService.saveCart(cart); + log.debug("AddItemCommand executed, updated cart: {}", updatedCart); + return updatedCart; + } + + @Override + public Cart undo() { + log.debug("Undoing AddItemCommand for customerId: {}, item: {}", customerId, newItem); + Cart cart = cartService.getCartByCustomerId(customerId); + + Optional existingItem = cart.getItems().stream() + .filter(i -> i.getProductId().equals(newItem.getProductId())) + .findFirst(); + + if (existingItem.isPresent()) { + int newQuantity = existingItem.get().getQuantity() - newItem.getQuantity(); + if (newQuantity <= 0) { + log.debug("Removing item during undo for productId: {}", newItem.getProductId()); + cart.getItems().removeIf(i -> i.getProductId().equals(newItem.getProductId())); + } else { + log.debug("Reducing quantity during undo for productId: {}", newItem.getProductId()); + existingItem.get().setQuantity(newQuantity); + } + } else { + log.warn("Item not found during undo for productId: {}", newItem.getProductId()); + } + + Cart updatedCart = cartService.saveCart(cart); + log.debug("AddItemCommand undone, updated cart: {}", updatedCart); + return updatedCart; + } +} diff --git a/src/main/java/cart/service/CartCommand.java b/src/main/java/cart/service/CartCommand.java new file mode 100644 index 0000000..da64aad --- /dev/null +++ b/src/main/java/cart/service/CartCommand.java @@ -0,0 +1,8 @@ +package cart.service; + +import cart.model.Cart; + +public interface CartCommand { + Cart execute(); + Cart undo(); +} diff --git a/src/main/java/cart/service/CartService.java b/src/main/java/cart/service/CartService.java new file mode 100644 index 0000000..cd53992 --- /dev/null +++ b/src/main/java/cart/service/CartService.java @@ -0,0 +1,184 @@ +package cart.service; + +import cart.exception.GlobalHandlerException; +import cart.model.Cart; +import cart.model.CartItem; +import cart.model.OrderRequest; +import cart.repository.CartRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.NoSuchElementException; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +@Slf4j +public class CartService { + + private final CartRepository cartRepository; + + private final RestTemplate restTemplate; + + @Value("${order.service.url}") + private String orderServiceUrl; + + + public Cart createCart(final String customerId) { + log.debug("Entering createCart" + + " with customerId:", customerId); + Cart cart = cartRepository.findByCustomerId(customerId) + .orElseGet(() -> { + Cart newCart = new Cart(UUID.randomUUID() + .toString(), customerId, new + ArrayList<>(), false); + log.debug("Cart created:", newCart); + return cartRepository.save(newCart); + }); + log.debug("Cart retrieved:", cart); + return cart; + } + + public Cart addItemToCart(final String customerId, + final CartItem newItem) { + log.debug("Entering addItemToCart " + + "with customerId:, newItem:", + customerId, newItem); + CartCommand command = new AddItemCommand(this, customerId, newItem); + return command.execute(); + } + + + public Cart updateItemQuantity(final String customerId, + final String productId, final int quantity) { + log.debug("Entering updateItemQuantity with" + + " customerId:, productId:, quantity: ", + customerId, productId, quantity); + CartCommand command = new UpdateQuantityCommand(this, customerId, productId, quantity); + return command.execute(); + } + + + public Cart removeItemFromCart(final String customerId, + final String productId) { + log.debug("Entering removeItemFromCart" + + " with customerId:, productId:", customerId, productId); + + CartCommand command = new RemoveItemCommand(this, customerId, productId); + return command.execute(); + } + + public void deleteCartByCustomerId(final String customerId) { + log.debug("Entering deleteCartByCustomerId" + + " with customerId:", customerId); + cartRepository.findByCustomerId(customerId) + .ifPresent(cart -> { + log.debug("Deleting cart for customerId:", customerId); + cartRepository.delete(cart); + }); + log.debug("Cart deletion completed for" + + " customerId:", customerId); + } + + public Cart getCartByCustomerId(final String customerId) { + log.debug("Entering getCartByCustomerId" + + " with customerId:", customerId); + Cart cart = cartRepository.findByCustomerId(customerId) + .orElseThrow(() -> { + log.error("Cart not found for customerId:", customerId); + throw new GlobalHandlerException( + HttpStatus.NOT_FOUND, "Cart not found"); + }); + log.debug("Cart retrieved:", cart); + return cart; + + } + + public void clearCart(final String customerId) { + log.debug("Entering clearCart with customerId:", customerId); + Cart cart = getCartByCustomerId(customerId); + cart.getItems().clear(); + cartRepository.save(cart); + log.debug("Cart cleared for customerId:", customerId); + } + + public Cart archiveCart(final String customerId) { + log.debug("Entering archiveCart with customerId:", customerId); + Cart cart = getActiveCart(customerId); + cart.setArchived(true); + Cart archivedCart = cartRepository.save(cart); + log.debug("Cart archived: {}", archivedCart); + return archivedCart; + } + + public Cart unarchiveCart(final String customerId) { + log.debug("Entering unarchiveCart with customerId:", customerId); + Cart cart = getArchivedCart(customerId); + cart.setArchived(false); + Cart activeCart = cartRepository.save(cart); + log.debug("Cart unarchived:", activeCart); + return activeCart; + } + + public Cart checkoutCart(final String customerId) { + log.debug("Entering checkoutCart with customerId:", customerId); + Cart cart = getActiveCart(customerId); + + OrderRequest orderRequest = new OrderRequest(); + orderRequest.setCustomerId(customerId); + orderRequest.setItems(cart.getItems()); + + try { + log.debug("Sending order request to" + + " Order Service for customerId:", customerId); + restTemplate.postForObject(orderServiceUrl + + "/orders", orderRequest, Void.class); + cart.getItems().clear(); + Cart updatedCart = cartRepository.save(cart); + log.debug("Cart checked out and cleared:", updatedCart); + return updatedCart; + } catch (Exception e) { + log.error("Failed to checkout cart for customerId:", customerId, e); + throw new RuntimeException("Error" + + " communicating with Order Service", e); + } + } + + + private Cart getActiveCart(final String customerId) { + log.debug("Entering getActiveCart with customerId:", customerId); + Cart cart = cartRepository.findByCustomerIdAndArchived(customerId, + false) + .orElseThrow(() -> { + log.error("Active cart not found" + + " for customerId:", customerId); + return new NoSuchElementException("Cart not" + + " found for customer ID: " + customerId); + }); + log.debug("Active cart retrieved:", cart); + return cart; + } + + private Cart getArchivedCart(final String customerId) { + log.debug("Entering getArchivedCart with customerId:", customerId); + Cart cart = cartRepository.findByCustomerIdAndArchived(customerId, true) + .orElseThrow(() -> { + log.error("Archived cart not found" + + " for customerId:", customerId); + return new NoSuchElementException("No archived " + + "cart found for customer ID: " + customerId); + }); + log.debug("Archived cart retrieved:", cart); + return cart; + } + + public Cart saveCart(final Cart cart) { + return cartRepository.save(cart); + } + +} diff --git a/src/main/java/cart/service/RemoveItemCommand.java b/src/main/java/cart/service/RemoveItemCommand.java new file mode 100644 index 0000000..1486f4a --- /dev/null +++ b/src/main/java/cart/service/RemoveItemCommand.java @@ -0,0 +1,57 @@ +package cart.service; + +import cart.model.Cart; +import cart.model.CartItem; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import java.util.Optional; + +@RequiredArgsConstructor +@Slf4j +public class RemoveItemCommand implements CartCommand { + + private final CartService cartService; + private final String customerId; + private final String productId; + private CartItem removedItem; + + @Override + public Cart execute() { + log.debug("Executing RemoveItemCommand for customerId: {}, productId: {}", customerId, productId); + Cart cart = cartService.getCartByCustomerId(customerId); + + Optional itemToRemove = cart.getItems().stream() + .filter(i -> i.getProductId().equals(productId)) + .findFirst(); + + if (itemToRemove.isPresent()) { + removedItem = new CartItem(itemToRemove.get().getProductId(), itemToRemove.get().getQuantity()); + cart.getItems().removeIf(i -> i.getProductId().equals(productId)); + log.debug("Item removed for productId: {}", productId); + } else { + log.warn("Item not found for removal, productId: {}", productId); + } + + Cart updatedCart = cartService.saveCart(cart); + log.debug("RemoveItemCommand executed, updated cart: {}", updatedCart); + return updatedCart; + } + + @Override + public Cart undo() { + log.debug("Undoing RemoveItemCommand for customerId: {}, productId: {}", customerId, productId); + Cart cart = cartService.getCartByCustomerId(customerId); + + if (removedItem != null) { + log.debug("Restoring item during undo for productId: {}", productId); + cart.getItems().add(removedItem); + } else { + log.warn("No item to restore during undo for productId: {}", productId); + } + + Cart updatedCart = cartService.saveCart(cart); + log.debug("RemoveItemCommand undone, updated cart: {}", updatedCart); + return updatedCart; + } +} diff --git a/src/main/java/cart/service/UpdateQuantityCommand.java b/src/main/java/cart/service/UpdateQuantityCommand.java new file mode 100644 index 0000000..0b3f4b7 --- /dev/null +++ b/src/main/java/cart/service/UpdateQuantityCommand.java @@ -0,0 +1,92 @@ +package cart.service; + +import cart.exception.GlobalHandlerException; +import cart.model.Cart; +import cart.model.CartItem; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; + +import java.util.Optional; + +@RequiredArgsConstructor +@Slf4j +public class UpdateQuantityCommand implements CartCommand { + + private final CartService cartService; + private final String customerId; + private final String productId; + private final int newQuantity; + private Integer previousQuantity; + + @Override + public Cart execute() { + log.debug("Executing UpdateQuantityCommand " + + "for customerId: {}, productId: {}, quantity: " + + "{}", customerId, productId, newQuantity); + Cart cart = cartService.getCartByCustomerId(customerId); + + Optional existingItemOpt = cart.getItems().stream() + .filter(i -> i.getProductId().equals(productId)) + .findFirst(); + + if (existingItemOpt.isEmpty()) { + log.error("Product not found in cart for " + + "productId: {}", productId); + throw new GlobalHandlerException( + HttpStatus.NOT_FOUND, "Product not found in cart"); + } + + CartItem item = existingItemOpt.get(); + previousQuantity = item.getQuantity(); + + if (newQuantity <= 0) { + log.debug("Removing item as quantity <= 0 for" + + " productId: {}", productId); + cart.getItems().remove(item); + } else { + log.debug("Updating quantity to: {} for " + + "productId: {}", newQuantity, productId); + item.setQuantity(newQuantity); + } + + Cart updatedCart = cartService.saveCart(cart); + log.debug("UpdateQuantityCommand executed, updated cart: {}", updatedCart); + return updatedCart; + } + + @Override + public Cart undo() { + log.debug("Undoing UpdateQuantityCommand for" + + " customerId: {}, productId: {}", customerId, productId); + Cart cart = cartService.getCartByCustomerId(customerId); + + if (previousQuantity == null) { + log.warn("No previous quantity to restore for productId: {}", productId); + return cart; + } + + Optional existingItemOpt = cart.getItems().stream() + .filter(i -> i.getProductId().equals(productId)) + .findFirst(); + + if (previousQuantity <= 0) { + log.debug("Restoring removed item during " + + "undo for productId: {}", productId); + cart.getItems().add(new CartItem(productId, previousQuantity)); + } else if (existingItemOpt.isPresent()) { + log.debug("Restoring previous quantity " + + "during undo for productId: {}", productId); + existingItemOpt.get().setQuantity(previousQuantity); + } else { + log.debug("Adding item back during" + + " undo for productId: {}", productId); + cart.getItems().add(new CartItem(productId, previousQuantity)); + } + + Cart updatedCart = cartService.saveCart(cart); + log.debug("UpdateQuantityCommand undone," + + " updated cart: {}", updatedCart); + return updatedCart; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..f14db7a --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,5 @@ +order.service.url=http://order-service:8082 +spring.data.mongodb.uri=mongodb://localhost:27018/cartDB +logging.file.name=./logs/app.log +logging.level.root=info +logging.level.com.podzilla.cart=debug \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..39be967 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,15 @@ + + + + logs/app.log + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/java/api/CartControllerTests.java b/src/test/java/api/CartControllerTests.java new file mode 100644 index 0000000..919e57d --- /dev/null +++ b/src/test/java/api/CartControllerTests.java @@ -0,0 +1,325 @@ +//package api; +// +//import cart.model.Cart; +//import cart.model.CartItem; +//import cart.repository.CartRepository; +//import com.fasterxml.jackson.databind.ObjectMapper; +//import lombok.RequiredArgsConstructor; +//import org.junit.jupiter.api.AfterEach; +//import org.junit.jupiter.api.BeforeEach; +//import org.junit.jupiter.api.Test; +//import org.springframework.beans.factory.annotation.Value; +//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +//import org.springframework.boot.test.context.SpringBootTest; +//import org.springframework.http.HttpMethod; +//import org.springframework.http.MediaType; +//import org.springframework.test.context.ActiveProfiles; +//import org.springframework.test.web.client.ExpectedCount; +//import org.springframework.test.web.client.MockRestServiceServer; +//import org.springframework.test.web.servlet.MockMvc; +//import org.springframework.web.client.RestTemplate; +// +//import java.util.ArrayList; +//import java.util.List; +//import java.util.UUID; +// +//import static org.hamcrest.Matchers.*; +//import static org.junit.jupiter.api.Assertions.*; +//import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +//import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +//import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +//import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; +//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +// +//@SpringBootTest +//@AutoConfigureMockMvc +//@RequiredArgsConstructor +//@ActiveProfiles("test") +//public class CartControllerTests { +// +// private MockMvc mockMvc; +// +// private CartRepository cartRepository; +// +// private ObjectMapper objectMapper; +// +// private RestTemplate restTemplate; +// +// private MockRestServiceServer mockServer; +// +// @Value("${order.service.url}") +// private String orderServiceUrl; +// +// private String customerId; +// private String productId1; +// private String productId2; +// +// @BeforeEach +// void setUp() { +// // Initialize MockRestServiceServer +// mockServer = MockRestServiceServer.createServer(restTemplate); +// +// cartRepository.deleteAll(); // Clean slate before each test +// +// customerId = "cust-" + UUID.randomUUID().toString(); +// productId1 = "prod-" + UUID.randomUUID().toString(); +// productId2 = "prod-" + UUID.randomUUID().toString(); +// } +// +// @AfterEach +// void tearDown() { +// cartRepository.deleteAll(); // Clean up after each test +// mockServer.verify(); // Verify all expected RestTemplate calls were made +// } +// +// private Cart createAndSaveTestCart(String custId, boolean archived, CartItem... items) { +// Cart cart = new Cart(UUID.randomUUID().toString(), custId, new ArrayList<>(List.of(items)), archived); +// return cartRepository.save(cart); +// } +// +// @Test +// void createCart_shouldCreateNewCart_whenCartDoesNotExist() throws Exception { +// mockMvc.perform(post("/api/carts/create/{customerId}", customerId)) +// .andExpect(status().isOk()) +// .andExpect(content().contentType(MediaType.APPLICATION_JSON)) +// .andExpect(jsonPath("$.customerId", is(customerId))) +// .andExpect(jsonPath("$.items", empty())) +// .andExpect(jsonPath("$.archived", is(false))); +// +// assertTrue(cartRepository.findByCustomerId(customerId).isPresent()); +// } +// +// @Test +// void createCart_shouldReturnExistingCart_whenCartExists() throws Exception { +// Cart existingCart = createAndSaveTestCart(customerId, false, new CartItem(productId1, 1)); +// +// mockMvc.perform(post("/api/carts/create/{customerId}", customerId)) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.id", is(existingCart.getId()))) +// .andExpect(jsonPath("$.customerId", is(customerId))) +// .andExpect(jsonPath("$.items[0].productId", is(productId1))); +// +// assertEquals(1, cartRepository.count()); +// } +// +// @Test +// void getCartByCustomerId_shouldReturnCart_whenExists() throws Exception { +// Cart cart = createAndSaveTestCart(customerId, false, new CartItem(productId1, 2)); +// +// mockMvc.perform(get("/api/carts/customer/{customerId}", customerId)) +// .andExpect(status().isOk()) +// .andExpect(content().contentType(MediaType.APPLICATION_JSON)) +// .andExpect(jsonPath("$.id", is(cart.getId()))) +// .andExpect(jsonPath("$.items[0].productId", is(productId1))) +// .andExpect(jsonPath("$.items[0].quantity", is(2))); +// } +// +// @Test +// void getCartByCustomerId_shouldReturnNotFound_whenNotExists() throws Exception { +// mockMvc.perform(get("/api/carts/customer/{customerId}", "non-existent-customer")) +// .andExpect(status().isNotFound()); +// } +// +// @Test +// void deleteCart_shouldDeleteCartAndReturnNoContent() throws Exception { +// createAndSaveTestCart(customerId, false); +// +// mockMvc.perform(delete("/api/carts/customer/{customerId}", customerId)) +// .andExpect(status().isNoContent()); +// +// assertFalse(cartRepository.findByCustomerId(customerId).isPresent()); +// } +// +// @Test +// void deleteCart_shouldDoNothingAndReturnNoContent_whenCartNotFound() throws Exception { +// mockMvc.perform(delete("/api/carts/customer/{customerId}", customerId)) +// .andExpect(status().isNoContent()); // Service method handles not found gracefully for delete +// } +// +// +// @Test +// void addItemToCart_shouldAddNewItemToExistingCart() throws Exception { +// createAndSaveTestCart(customerId, false); +// CartItem newItem = new CartItem(productId1, 3); +// +// mockMvc.perform(post("/api/carts/{customerId}/items", customerId) +// .contentType(MediaType.APPLICATION_JSON) +// .content(objectMapper.writeValueAsString(newItem))) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.items", hasSize(1))) +// .andExpect(jsonPath("$.items[0].productId", is(productId1))) +// .andExpect(jsonPath("$.items[0].quantity", is(3))); +// +// Cart updatedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertEquals(1, updatedCart.getItems().size()); +// assertEquals(productId1, updatedCart.getItems().get(0).getProductId()); +// } +// +// @Test +// void addItemToCart_shouldUpdateQuantityIfItemExists() throws Exception { +// createAndSaveTestCart(customerId, false, new CartItem(productId1, 2)); +// CartItem itemToAdd = new CartItem(productId1, 3); // Adding more of the same item +// +// mockMvc.perform(post("/api/carts/{customerId}/items", customerId) +// .contentType(MediaType.APPLICATION_JSON) +// .content(objectMapper.writeValueAsString(itemToAdd))) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.items", hasSize(1))) +// .andExpect(jsonPath("$.items[0].productId", is(productId1))) +// .andExpect(jsonPath("$.items[0].quantity", is(5))); // 2 + 3 +// +// Cart updatedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertEquals(5, updatedCart.getItems().get(0).getQuantity()); +// } +// +// @Test +// void updateItemQuantity_shouldUpdateQuantityOfExistingItem() throws Exception { +// createAndSaveTestCart(customerId, false, new CartItem(productId1, 2)); +// int newQuantity = 5; +// +// mockMvc.perform(patch("/api/carts/{customerId}/items/{productId}", customerId, productId1) +// .param("quantity", String.valueOf(newQuantity))) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.items[0].quantity", is(newQuantity))); +// +// Cart updatedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertEquals(newQuantity, updatedCart.getItems().get(0).getQuantity()); +// } +// +// @Test +// void updateItemQuantity_shouldRemoveItemIfQuantityIsZero() throws Exception { +// createAndSaveTestCart(customerId, false, new CartItem(productId1, 2)); +// +// mockMvc.perform(patch("/api/carts/{customerId}/items/{productId}", customerId, productId1) +// .param("quantity", "0")) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.items", empty())); +// +// Cart updatedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertTrue(updatedCart.getItems().isEmpty()); +// } +// +// @Test +// void updateItemQuantity_shouldReturnNotFound_whenItemNotInCart() throws Exception { +// createAndSaveTestCart(customerId, false); // Cart exists but is empty +// +// mockMvc.perform(patch("/api/carts/{customerId}/items/{productId}", customerId, "non-existent-product") +// .param("quantity", "5")) +// .andExpect(status().isNotFound()); // Based on CartService logic throwing GlobalHandlerException +// } +// +// +// @Test +// void removeItemFromCart_shouldRemoveItem() throws Exception { +// createAndSaveTestCart(customerId, false, new CartItem(productId1, 1), new CartItem(productId2, 1)); +// +// mockMvc.perform(delete("/api/carts/{customerId}/items/{productId}", customerId, productId1)) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.items", hasSize(1))) +// .andExpect(jsonPath("$.items[0].productId", is(productId2))); +// +// Cart updatedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertEquals(1, updatedCart.getItems().size()); +// assertEquals(productId2, updatedCart.getItems().get(0).getProductId()); +// } +// +// @Test +// void clearCart_shouldRemoveAllItemsFromCart() throws Exception { +// createAndSaveTestCart(customerId, false, new CartItem(productId1, 1), new CartItem(productId2, 1)); +// +// mockMvc.perform(delete("/api/carts/{customerId}/clear", customerId)) +// .andExpect(status().isNoContent()); +// +// Cart clearedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertTrue(clearedCart.getItems().isEmpty()); +// } +// +// @Test +// void archiveCart_shouldSetArchivedToTrue() throws Exception { +// createAndSaveTestCart(customerId, false, new CartItem(productId1, 1)); +// +// mockMvc.perform(patch("/api/carts/{customerId}/archive", customerId)) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.archived", is(true))); +// +// Cart archivedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertTrue(archivedCart.isArchived()); +// } +// +// @Test +// void archiveCart_shouldReturnNotFound_whenActiveCartNotExists() throws Exception { +// // Ensure no active cart exists or only an archived one +// createAndSaveTestCart(customerId, true); // Save an already archived cart +// +// mockMvc.perform(patch("/api/carts/{customerId}/archive", customerId)) +// .andExpect(status().isNotFound()); // Because getActiveCart will throw NoSuchElementException +// } +// +// @Test +// void unarchiveCart_shouldSetArchivedToFalse() throws Exception { +// createAndSaveTestCart(customerId, true, new CartItem(productId1, 1)); // Start with an archived cart +// +// mockMvc.perform(patch("/api/carts/{customerId}/unarchive", customerId)) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.archived", is(false))); +// +// Cart unarchivedCart = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertFalse(unarchivedCart.isArchived()); +// } +// +// @Test +// void unarchiveCart_shouldReturnNotFound_whenArchivedCartNotExists() throws Exception { +// // Ensure no archived cart exists or only an active one +// createAndSaveTestCart(customerId, false); // Save an active cart +// +// mockMvc.perform(patch("/api/carts/{customerId}/unarchive", customerId)) +// .andExpect(status().isNotFound()); // Because getArchivedCart will throw NoSuchElementException +// } +// +// @Test +// void checkoutCart_shouldClearCartAndCallOrderService_whenSuccessful() throws Exception { +// Cart cartToCheckout = createAndSaveTestCart(customerId, false, new CartItem(productId1, 2), new CartItem(productId2, 1)); +// +// // Expect a POST request to the order service +// mockServer.expect(ExpectedCount.once(), +// requestTo(orderServiceUrl + "/orders")) +// .andExpect(method(HttpMethod.POST)) +// // You can add more specific assertions for the request body if needed: +// // .andExpect(content().json(objectMapper.writeValueAsString(expectedOrderRequest))) +// .andRespond(withSuccess()); // Simulate a successful response from Order Service +// +// mockMvc.perform(post("/api/carts/{customerId}/checkout", customerId)) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.customerId", is(customerId))) +// .andExpect(jsonPath("$.items", empty())); // Cart items should be cleared +// +// Cart finalCartState = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertTrue(finalCartState.getItems().isEmpty()); +// assertFalse(finalCartState.isArchived()); // Should remain active but empty +// } +// +// @Test +// void checkoutCart_shouldReturnInternalServerError_whenOrderServiceFails() throws Exception { +// createAndSaveTestCart(customerId, false, new CartItem(productId1, 1)); +// +// mockServer.expect(ExpectedCount.once(), +// requestTo(orderServiceUrl + "/orders")) +// .andExpect(method(HttpMethod.POST)) +// .andRespond(withServerError()); // Simulate an error from Order Service +// +// mockMvc.perform(post("/api/carts/{customerId}/checkout", customerId)) +// .andExpect(status().isInternalServerError()) // Based on your controller's exception handling +// .andExpect(content().string(containsString("Error communicating with Order Service"))); // Check error message +// +// // Cart should NOT be cleared if order service call fails +// Cart cartStateAfterFailure = cartRepository.findByCustomerId(customerId).orElseThrow(); +// assertFalse(cartStateAfterFailure.getItems().isEmpty()); +// } +// +// @Test +// void checkoutCart_shouldReturnNotFound_whenCartNotExists() throws Exception { +// mockMvc.perform(post("/api/carts/{customerId}/checkout", "non-existent-customer")) +// .andExpect(status().isNotFound()); +// } +//} \ No newline at end of file diff --git a/src/test/java/service/CartServiceTest.java b/src/test/java/service/CartServiceTest.java new file mode 100644 index 0000000..d7670d3 --- /dev/null +++ b/src/test/java/service/CartServiceTest.java @@ -0,0 +1,334 @@ +package service; +import cart.exception.GlobalHandlerException; +import cart.model.Cart; +import cart.model.CartItem; +import cart.model.OrderRequest; +import cart.repository.CartRepository; +import cart.service.CartService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class CartServiceTest { + + @Mock + private CartRepository cartRepository; + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private CartService cartService; + + private Cart cart; + private CartItem cartItem; + private final String customerId = "cust123"; + private final String productId = "prod456"; + private final String cartId = UUID.randomUUID().toString(); + private final String orderServiceUrl = "http://localhost:8080"; + + @BeforeEach + void setUp() { + // Initialize test data + cart = new Cart(cartId, customerId, new ArrayList<>(), false); + cartItem = new CartItem(productId, 1); + + // Set orderServiceUrl + ReflectionTestUtils.setField(cartService, "orderServiceUrl", orderServiceUrl); + } + + @Test + void createCart_existingCart_returnsCart() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + + Cart result = cartService.createCart(customerId); + + assertEquals(cart, result); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository, never()).save(any()); + } + + @Test + void createCart_noExistingCart_createsAndSavesCart() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.empty()); + when(cartRepository.save(any(Cart.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + Cart result = cartService.createCart(customerId); + + assertEquals(customerId, result.getCustomerId()); + assertFalse(result.isArchived()); + assertTrue(result.getItems().isEmpty()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).save(any(Cart.class)); + } + + @Test + void addItemToCart_newItem_addsItem() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + Cart result = cartService.addItemToCart(customerId, cartItem); + + assertEquals(1, result.getItems().size()); + assertEquals(cartItem.getProductId(), result.getItems().get(0).getProductId()); + assertEquals(cartItem.getQuantity(), result.getItems().get(0).getQuantity()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).save(cart); + } + + @Test + void addItemToCart_existingItem_updatesQuantity() { + cart.getItems().add(new CartItem(productId, 1)); + CartItem newItem = new CartItem(productId, 2); + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + Cart result = cartService.addItemToCart(customerId, newItem); + + assertEquals(1, result.getItems().size()); + assertEquals(3, result.getItems().get(0).getQuantity()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).save(cart); + } + + @Test + void addItemToCart_cartNotFound_throwsGlobalHandlerException() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.empty()); + + GlobalHandlerException exception = assertThrows(GlobalHandlerException.class, + () -> cartService.addItemToCart(customerId, cartItem)); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatus()); + assertEquals("Cart not found", exception.getMessage()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository, never()).save(any()); + } + + @Test + void updateItemQuantity_existingItem_updatesQuantity() { + cart.getItems().add(new CartItem(productId, 1)); + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + Cart result = cartService.updateItemQuantity(customerId, productId, 5); + + assertEquals(5, result.getItems().get(0).getQuantity()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).save(cart); + } + + @Test + void updateItemQuantity_quantityZero_removesItem() { + cart.getItems().add(new CartItem(productId, 1)); + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + Cart result = cartService.updateItemQuantity(customerId, productId, 0); + + assertTrue(result.getItems().isEmpty()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).save(cart); + } + + @Test + void updateItemQuantity_itemNotFound_throwsGlobalHandlerException() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + + GlobalHandlerException exception = assertThrows(GlobalHandlerException.class, + () -> cartService.updateItemQuantity(customerId, productId, 5)); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatus()); + assertEquals("Product not found in cart", exception.getMessage()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository, never()).save(any()); + } + + @Test + void removeItemFromCart_itemExists_removesItem() { + cart.getItems().add(new CartItem(productId, 1)); + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + Cart result = cartService.removeItemFromCart(customerId, productId); + + assertTrue(result.getItems().isEmpty()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).save(cart); + } + + @Test + void removeItemFromCart_cartNotFound_throwsGlobalHandlerException() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.empty()); + + GlobalHandlerException exception = assertThrows(GlobalHandlerException.class, + () -> cartService.removeItemFromCart(customerId, productId)); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatus()); + assertEquals("Cart not found", exception.getMessage()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository, never()).save(any()); + } + + @Test + void deleteCartByCustomerId_cartExists_deletesCart() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + + cartService.deleteCartByCustomerId(customerId); + + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).delete(cart); + } + + @Test + void deleteCartByCustomerId_cartNotFound_doesNothing() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.empty()); + + cartService.deleteCartByCustomerId(customerId); + + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository, never()).delete(any()); + } + + @Test + void getCartByCustomerId_cartExists_returnsCart() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + + Cart result = cartService.getCartByCustomerId(customerId); + + assertEquals(cart, result); + verify(cartRepository).findByCustomerId(customerId); + } + + @Test + void getCartByCustomerId_cartNotFound_throwsGlobalHandlerException() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.empty()); + + GlobalHandlerException exception = assertThrows(GlobalHandlerException.class, + () -> cartService.getCartByCustomerId(customerId)); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatus()); + assertEquals("Cart not found", exception.getMessage()); + verify(cartRepository).findByCustomerId(customerId); + } + + @Test + void clearCart_cartExists_clearsItems() { + cart.getItems().add(new CartItem(productId, 1)); + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + cartService.clearCart(customerId); + + assertTrue(cart.getItems().isEmpty()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository).save(cart); + } + + @Test + void clearCart_cartNotFound_throwsGlobalHandlerException() { + when(cartRepository.findByCustomerId(customerId)).thenReturn(Optional.empty()); + + GlobalHandlerException exception = assertThrows(GlobalHandlerException.class, + () -> cartService.clearCart(customerId)); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatus()); + assertEquals("Cart not found", exception.getMessage()); + verify(cartRepository).findByCustomerId(customerId); + verify(cartRepository, never()).save(any()); + } + + @Test + void archiveCart_activeCart_archivesCart() { + when(cartRepository.findByCustomerIdAndArchived(customerId, false)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + Cart result = cartService.archiveCart(customerId); + + assertTrue(result.isArchived()); + verify(cartRepository).findByCustomerIdAndArchived(customerId, false); + verify(cartRepository).save(cart); + } + + @Test + void archiveCart_noActiveCart_throwsNoSuchElementException() { + when(cartRepository.findByCustomerIdAndArchived(customerId, false)).thenReturn(Optional.empty()); + + assertThrows(NoSuchElementException.class, () -> cartService.archiveCart(customerId)); + verify(cartRepository).findByCustomerIdAndArchived(customerId, false); + verify(cartRepository, never()).save(any()); + } + + @Test + void unarchiveCart_archivedCart_unarchivesCart() { + cart.setArchived(true); + when(cartRepository.findByCustomerIdAndArchived(customerId, true)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + + Cart result = cartService.unarchiveCart(customerId); + + assertFalse(result.isArchived()); + verify(cartRepository).findByCustomerIdAndArchived(customerId, true); + verify(cartRepository).save(cart); + } + + @Test + void unarchiveCart_noArchivedCart_throwsNoSuchElementException() { + when(cartRepository.findByCustomerIdAndArchived(customerId, true)).thenReturn(Optional.empty()); + + assertThrows(NoSuchElementException.class, () -> cartService.unarchiveCart(customerId)); + verify(cartRepository).findByCustomerIdAndArchived(customerId, true); + verify(cartRepository, never()).save(any()); + } + + @Test + void checkoutCart_validCart_sendsToOrderServiceAndClearsCart() { + cart.getItems().add(new CartItem(productId, 1)); + when(cartRepository.findByCustomerIdAndArchived(customerId, false)).thenReturn(Optional.of(cart)); + when(cartRepository.save(any(Cart.class))).thenReturn(cart); + when(restTemplate.postForObject(eq(orderServiceUrl + "/orders"), any(OrderRequest.class), eq(Void.class))) + .thenReturn(null); + + Cart result = cartService.checkoutCart(customerId); + + assertTrue(result.getItems().isEmpty()); + verify(cartRepository).findByCustomerIdAndArchived(customerId, false); + verify(restTemplate).postForObject(eq(orderServiceUrl + "/orders"), any(OrderRequest.class), eq(Void.class)); + verify(cartRepository).save(cart); + } + + @Test + void checkoutCart_noActiveCart_throwsNoSuchElementException() { + when(cartRepository.findByCustomerIdAndArchived(customerId, false)).thenReturn(Optional.empty()); + + assertThrows(NoSuchElementException.class, () -> cartService.checkoutCart(customerId)); + verify(cartRepository).findByCustomerIdAndArchived(customerId, false); + verify(restTemplate, never()).postForObject(any(), any(), any()); + verify(cartRepository, never()).save(any()); + } + + @Test + void checkoutCart_orderServiceFails_throwsRuntimeException() { + cart.getItems().add(new CartItem(productId, 1)); + when(cartRepository.findByCustomerIdAndArchived(customerId, false)).thenReturn(Optional.of(cart)); + when(restTemplate.postForObject(eq(orderServiceUrl + "/orders"), any(OrderRequest.class), eq(Void.class))) + .thenThrow(new RuntimeException("Order Service error")); + + RuntimeException exception = assertThrows(RuntimeException.class, () -> cartService.checkoutCart(customerId)); + assertEquals("Error communicating with Order Service", exception.getMessage()); + verify(cartRepository).findByCustomerIdAndArchived(customerId, false); + verify(restTemplate).postForObject(eq(orderServiceUrl + "/orders"), any(OrderRequest.class), eq(Void.class)); + verify(cartRepository, never()).save(any()); + } +} \ No newline at end of file diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 0000000..a38ed3d --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,4 @@ +spring.data.mongodb.uri=mongodb://localhost:27017/testdb +spring.data.mongodb.database=testdb +spring.main.banner-mode= off +spring.main.log-startup-info=false \ No newline at end of file