Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/nashtech-garage/yas into fe…
Browse files Browse the repository at this point in the history
…ature/1003-payment-provider

# Conflicts:
#	payment-paypal/src/main/java/com/yas/payment/paypal/service/OrderService.java
#	payment-paypal/src/main/java/com/yas/payment/paypal/service/PaypalService.java
#	payment-paypal/src/main/java/com/yas/payment/paypal/viewmodel/OrderVm.java
#	payment-paypal/src/main/java/com/yas/paymentpaypal/config/ServiceUrlConfig.java
#	payment-paypal/src/main/java/com/yas/paymentpaypal/service/PaymentService.java
#	payment-paypal/src/main/resources/application.properties
#	payment-paypal/src/test/java/com/yas/payment/paypal/service/OrderServiceTest.java
#	payment-paypal/src/test/java/com/yas/payment/paypal/service/PaypalServiceTest.java
#	payment-paypal/src/test/java/com/yas/paymentpaypal/service/PaymentServiceTest.java
#	payment/src/main/java/com/yas/payment/service/OrderService.java
  • Loading branch information
khanhtranduy committed Oct 28, 2024
2 parents 8df2beb + 5e44987 commit fd8d658
Show file tree
Hide file tree
Showing 14 changed files with 159 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import com.yas.cart.viewmodel.CartItemPutVm;
import com.yas.commonlibrary.exception.ApiExceptionHandler;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
Expand All @@ -30,6 +29,7 @@
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ public ResponseEntity<OrderVm> getOrderWithItemsById(@PathVariable long id) {
return ResponseEntity.ok(orderService.getOrderWithItemsById(id));
}

@GetMapping("/storefront/orders/checkout/{id}")
public ResponseEntity<OrderGetVm> getOrderWithCheckoutId(@PathVariable String id) {
return ResponseEntity.ok(orderService.findOrderVmByCheckoutId(id));
}

@GetMapping("/backoffice/orders")
public ResponseEntity<OrderListVm> getOrders(
@RequestParam(value = "createdFrom", defaultValue = "#{new java.util.Date(1970-01-01)}", required = false)
Expand Down
5 changes: 5 additions & 0 deletions order/src/main/java/com/yas/order/service/OrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,11 @@ public List<OrderGetVm> getMyOrders(String productName, OrderStatus orderStatus)
return orders.stream().map(OrderGetVm::fromModel).toList();
}

public OrderGetVm findOrderVmByCheckoutId(String checkoutId) {
Order order = this.findOrderByCheckoutId(checkoutId);
return OrderGetVm.fromModel(order);
}

public Order findOrderByCheckoutId(String checkoutId) {
return this.orderRepository.findByCheckoutId(checkoutId)
.orElseThrow(() -> new NotFoundException(ORDER_NOT_FOUND, "of checkoutId " + checkoutId));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,13 @@ public record OrderVm(
DeliveryMethod deliveryMethod,
DeliveryStatus deliveryStatus,
PaymentStatus paymentStatus,
Set<OrderItemVm> orderItemVms
Set<OrderItemVm> orderItemVms,
String checkoutId

) {
public static OrderVm fromModel(Order order) {
Set<OrderItemVm> orderItemVms = order.getOrderItems().stream().map(
item -> OrderItemVm.fromModel(item))
OrderItemVm::fromModel)
.collect(Collectors.toSet());

return OrderVm.builder()
Expand All @@ -53,6 +54,7 @@ public static OrderVm fromModel(Order order) {
.deliveryStatus(order.getDeliveryStatus())
.paymentStatus(order.getPaymentStatus())
.orderItemVms(orderItemVms)
.checkoutId(order.getCheckoutId())
.build();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand Down Expand Up @@ -225,8 +226,7 @@ void testGetLatestOrders_whenRequestIsValid_thenReturnOrderListVm() throws Excep
}

@Test
void testExportCsv_whenRequestIsValid_thenReturnCsvFile() throws Exception
{
void testExportCsv_whenRequestIsValid_thenReturnCsvFile() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
OrderRequest orderRequest = new OrderRequest();
Expand Down Expand Up @@ -296,7 +296,8 @@ private OrderVm getOrderVm() {
DeliveryMethod.GRAB_EXPRESS,
DeliveryStatus.PREPARING,
PaymentStatus.COMPLETED,
items
items,
UUID.randomUUID().toString()
);
}

Expand Down Expand Up @@ -412,4 +413,4 @@ private List<OrderItemPostVm> getOrderItemPostVms() {
return List.of(item1, item2);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -83,7 +84,8 @@ void testDeleteCartItems_ifNormalCase_shouldNoException() {
DeliveryMethod.GRAB_EXPRESS,
DeliveryStatus.CANCELLED,
PaymentStatus.PENDING,
items
items,
UUID.randomUUID().toString()
);
}

Expand Down Expand Up @@ -118,4 +120,4 @@ void testDeleteCartItems_ifNormalCase_shouldNoException() {
items.add(item2);
return items;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.yas.payment.paypal.service;

import com.yas.paymentpaypal.config.ServiceUrlConfig;
import com.yas.payment.paypal.viewmodel.OrderVm;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import java.net.URI;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderService extends AbstractCircuitBreakFallbackHandler {
private final RestClient restClient;
private final ServiceUrlConfig serviceUrlConfig;

@Retry(name = "restApi")
@CircuitBreaker(name = "restCircuitBreaker", fallbackMethod = "handleBodilessFallback")
public OrderVm getOrderByCheckoutId(String checkoutId) {
final String jwt =
((Jwt) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getTokenValue();
final URI url = UriComponentsBuilder
.fromHttpUrl(serviceUrlConfig.order())
.path("/storefront/orders/checkout/" + checkoutId)
.buildAndExpand()
.toUri();

return restClient.get()
.uri(url)
.headers(h -> h.setBearerAuth(jwt))
.retrieve()
.body(OrderVm.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ public PaypalCreatePaymentResponse createPayment(PaypalCreatePaymentRequest crea
HttpResponse<Order> orderHttpResponse = payPalHttpClient.execute(ordersCreateRequest);
Order order = orderHttpResponse.result();
String redirectUrl = order.links().stream()
.filter(link -> "approve".equals(link.rel()))
.findFirst()
.orElseThrow(NoSuchElementException::new)
.href();
.filter(link -> "approve".equals(link.rel()))
.findFirst()
.orElseThrow(NoSuchElementException::new)
.href();

CheckoutIdHelper.setCheckoutId(createPaymentRequest.checkoutId());
return new PaypalCreatePaymentResponse("success", order.id(), redirectUrl);
Expand All @@ -87,7 +87,6 @@ public PaypalCapturePaymentResponse capturePayment(PaypalCapturePaymentRequest c
BigDecimal paymentFee = new BigDecimal(paypalFee);
BigDecimal amount = new BigDecimal(capture.amount().value());


PaypalCapturePaymentResponse capturedPayment = PaypalCapturePaymentResponse.builder()
.paymentFee(paymentFee)
.gatewayTransactionId(order.id())
Expand All @@ -104,4 +103,4 @@ public PaypalCapturePaymentResponse capturePayment(PaypalCapturePaymentRequest c
}
return PaypalCapturePaymentResponse.builder().failureMessage("Something Wrong!").build();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.yas.payment.paypal.viewmodel;

public record OrderVm(Long id) {
}
1 change: 0 additions & 1 deletion payment-paypal/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ logging.pattern.level=%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-

spring.security.oauth2.resourceserver.jwt.issuer-uri=http://identity/realms/Yas


spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

# The SQL dialect makes Hibernate generate better SQL for the chosen database
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//package com.yas.paymentpaypal.service;
//
//import static com.yas.paymentpaypal.utils.SecurityContextUtils.setUpSecurityContext;
//import static org.mockito.ArgumentMatchers.any;
//import static org.mockito.Mockito.mock;
//import static org.mockito.Mockito.times;
//import static org.mockito.Mockito.verify;
//import static org.mockito.Mockito.when;
//
//import com.yas.paymentpaypal.config.ServiceUrlConfig;
//import java.net.URI;
//import java.util.UUID;
//import org.junit.jupiter.api.BeforeEach;
//import org.junit.jupiter.api.Test;
//import org.mockito.Mockito;
//import org.springframework.web.client.RestClient;
//import org.springframework.web.util.UriComponentsBuilder;
//
//public class OrderServiceTest {
// private RestClient restClient;
//
// private ServiceUrlConfig serviceUrlConfig;
//
// private OrderService orderService;
//
// private RestClient.ResponseSpec responseSpec;
//
// private static final String ORDER_URL = "http://api.yas.local/order";
//
// @BeforeEach
// void setUp() {
// restClient = mock(RestClient.class);
// serviceUrlConfig = mock(ServiceUrlConfig.class);
// orderService = new OrderService(restClient, serviceUrlConfig);
// responseSpec = Mockito.mock(RestClient.ResponseSpec.class);
// setUpSecurityContext("test");
// when(serviceUrlConfig.order()).thenReturn(ORDER_URL);
// }
//
// @Test
// void testGetOrderByCheckoutId_ifNormalCase_returnOrderVm() {
// String checkoutId = UUID.randomUUID().toString();
//
// final URI url = UriComponentsBuilder
// .fromHttpUrl(serviceUrlConfig.order())
// .path("/storefront/orders/checkout/" + checkoutId)
// .buildAndExpand()
// .toUri();
//
// RestClient.RequestHeadersUriSpec requestBodyUriSpec = mock(RestClient.RequestHeadersUriSpec.class);
// when(restClient.get()).thenReturn(requestBodyUriSpec);
// when(requestBodyUriSpec.uri(url)).thenReturn(requestBodyUriSpec);
// when(requestBodyUriSpec.headers(any())).thenReturn(requestBodyUriSpec);
// when(requestBodyUriSpec.retrieve()).thenReturn(responseSpec);
//
// orderService.getOrderByCheckoutId(checkoutId);
//
// verify(restClient, times(1)).get();
// }
//}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@
import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import com.yas.payment.paypal.model.CheckoutIdHelper;
import com.yas.payment.paypal.viewmodel.PaypalCapturePaymentRequest;
import com.yas.payment.paypal.viewmodel.PaypalCapturePaymentResponse;
import com.yas.payment.paypal.viewmodel.PaypalCreatePaymentRequest;
import com.yas.payment.paypal.viewmodel.PaypalCreatePaymentResponse;
import com.yas.payment.paypal.viewmodel.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
Expand All @@ -30,6 +26,8 @@ class PaypalServiceTest {
private PayPalHttpClientInitializer payPalHttpClientInitializer;
private String paymentSettings = "{\"clientId\": \"abc\", \"clientSecret\": \"123\", \"mode\": \"sandbox\"}";

private OrderService orderService;

@BeforeEach
void setUp() {
payPalHttpClient = mock(PayPalHttpClient.class);
Expand Down Expand Up @@ -129,8 +127,11 @@ void testCapturePayment_whenStatusNotNull_returnCapturedPaymentVm() throws IOExc
.status("COMPLETED")
.purchaseUnits(purchaseUnitList);

OrderVm orderVmRes = new OrderVm(12L);

HttpResponse mockResponse = mock(HttpResponse.class);
when(payPalHttpClient.execute(any(OrdersCaptureRequest.class))).thenReturn(mockResponse);
when(orderService.getOrderByCheckoutId(any(String.class))).thenReturn(orderVmRes);
when(mockResponse.result()).thenReturn(mockOrder);

String token = "test-token-1";
Expand Down Expand Up @@ -172,4 +173,4 @@ void testCapturePayment_whenIoException_returnCapturedPaymentVm() throws IOExcep
assertEquals("error message", result.failureMessage());
}

}
}
22 changes: 11 additions & 11 deletions payment/src/main/java/com/yas/payment/service/OrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,20 @@ public Long updateCheckoutStatus(CapturePaymentResponse capturePaymentResponse)
@Retry(name = "restApi")
@CircuitBreaker(name = "restCircuitBreaker", fallbackMethod = "handlePaymentOrderStatusFallback")
public PaymentOrderStatusVm updateOrderStatus(PaymentOrderStatusVm orderPaymentStatusVm) {
final String jwt = ((Jwt) SecurityContextHolder.getContext().getAuthentication().getPrincipal())
.getTokenValue();
final String jwt =
((Jwt) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getTokenValue();
final URI url = UriComponentsBuilder
.fromHttpUrl(serviceUrlConfig.order())
.path("/storefront/orders/status")
.buildAndExpand()
.toUri();
.fromHttpUrl(serviceUrlConfig.order())
.path("/storefront/orders/status")
.buildAndExpand()
.toUri();

return restClient.put()
.uri(url)
.headers(h -> h.setBearerAuth(jwt))
.body(orderPaymentStatusVm)
.retrieve()
.body(PaymentOrderStatusVm.class);
.uri(url)
.headers(h -> h.setBearerAuth(jwt))
.body(orderPaymentStatusVm)
.retrieve()
.body(PaymentOrderStatusVm.class);
}

protected Long handleLongFallback(Throwable throwable) throws Throwable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

Expand Down Expand Up @@ -66,6 +69,7 @@ void testUpdateCheckoutStatus_whenNormalCase_returnLong() {
when(restClient.put()).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.uri(url)).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.body(any(CheckoutStatusVm.class))).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.headers(any())).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.retrieve()).thenReturn(responseSpec);
when(responseSpec.body(Long.class)).thenReturn(1L);

Expand All @@ -78,6 +82,7 @@ void testUpdateCheckoutStatus_whenNormalCase_returnLong() {
@Test
void testUpdateOrderStatus_whenNormalCase_returnPaymentOrderStatusVm() {


PaymentOrderStatusVm statusVm = PaymentOrderStatusVm.builder()
.orderId(123456L)
.orderStatus("COMPLETED")
Expand All @@ -95,6 +100,7 @@ void testUpdateOrderStatus_whenNormalCase_returnPaymentOrderStatusVm() {
when(restClient.put()).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.uri(url)).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.body(statusVm)).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.headers(any())).thenReturn(requestBodyUriSpec);
when(requestBodyUriSpec.retrieve()).thenReturn(responseSpec);
when(responseSpec.body(PaymentOrderStatusVm.class)).thenReturn(statusVm);

Expand All @@ -104,4 +110,4 @@ void testUpdateOrderStatus_whenNormalCase_returnPaymentOrderStatusVm() {
assertThat(result.paymentId()).isEqualTo(78910L);
assertThat(result.paymentStatus()).isEqualTo("SUCCESS");
}
}
}

0 comments on commit fd8d658

Please sign in to comment.