Add pricing calculation

Problem Context

We need to calculate item prices with tax in both the shopping cart preview and the checkout process.

Advanced
200 points

File Changes (2)

src/main/java/com/example/service/CartService.java MODIFIED
@@ -20 +20 @@
20 20 private final CartRepository cartRepository;
21 +
22 + public CartSummary getCartSummary(Long userId) {
23 + Cart cart = cartRepository.findByUserId(userId);
24 + BigDecimal subtotal = BigDecimal.ZERO;
25 +
26 + for (CartItem item : cart.getItems()) {
27 + BigDecimal itemPrice = item.getProduct().getPrice()
28 + .multiply(BigDecimal.valueOf(item.getQuantity()));
29 +
30 + // Apply product discount
31 + if (item.getProduct().getDiscountPercent() > 0) {
32 + BigDecimal discount = itemPrice.multiply(
33 + BigDecimal.valueOf(item.getProduct().getDiscountPercent() / 100.0));
34 + itemPrice = itemPrice.subtract(discount);
35 + }
36 + subtotal = subtotal.add(itemPrice);
37 + }
38 +
39 + // Calculate tax (8%)
40 + BigDecimal tax = subtotal.multiply(new BigDecimal("0.08"));
41 + BigDecimal total = subtotal.add(tax);
42 +
43 + return new CartSummary(subtotal, tax, total);
44 + }
21 45 }
src/main/java/com/example/service/CheckoutService.java MODIFIED
@@ -30 +30 @@
30 30 private final PaymentService paymentService;
31 +
32 + public Order checkout(Long userId, CheckoutRequest request) {
33 + Cart cart = cartRepository.findByUserId(userId);
34 + BigDecimal subtotal = BigDecimal.ZERO;
35 +
36 + for (CartItem item : cart.getItems()) {
37 + BigDecimal itemPrice = item.getProduct().getPrice()
38 + .multiply(BigDecimal.valueOf(item.getQuantity()));
39 +
40 + // Apply product discount
41 + if (item.getProduct().getDiscountPercent() > 0) {
42 + BigDecimal discount = itemPrice.multiply(
43 + BigDecimal.valueOf(item.getProduct().getDiscountPercent() / 100.0));
44 + itemPrice = itemPrice.subtract(discount);
45 + }
46 + subtotal = subtotal.add(itemPrice);
47 + }
48 +
49 + // Calculate tax (8%)
50 + BigDecimal tax = subtotal.multiply(new BigDecimal("0.08"));
51 + BigDecimal total = subtotal.add(tax);
52 +
53 + // Process payment and create order...
54 + return orderService.createOrder(userId, cart, total);
55 + }
31 56 }
Login Required: You must be registered to submit reviews and receive AI feedback. Register or login to start reviewing!

Your Review

Tip: Be thorough! Consider security, performance, code quality, and best practices.
Review Tips
  • Look for security vulnerabilities (SQL injection, XSS, etc.)
  • Check for null pointer exceptions and error handling
  • Consider performance implications
  • Evaluate code maintainability and readability
  • Check for proper resource management
  • Look for logic errors or edge cases
Analyzing Your Review
Our AI is carefully evaluating your code review against best practices