Skip to content

Commit

Permalink
Added restaurantName to OrderCreatedEvent and changed to Order Histor…
Browse files Browse the repository at this point in the history
…y Service to use it
  • Loading branch information
cer committed Jun 10, 2018
1 parent 8a0f905 commit 87938c4
Show file tree
Hide file tree
Showing 21 changed files with 147 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
- restore_cache:
key: ftgo-application-{{ checksum "build.gradle" }}
- run: TERM=dumb ./build-contracts.sh
- run: TERM=dumb ./gradlew testClasses
- run: TERM=dumb ./gradlew testClasses :ftgo-order-service:compileComponentTestJava
- save_cache:
paths:
- ~/.gradle
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@
import java.util.Collections;

import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class EndToEndTests {

// TODO Move to a shared module

public static final String CHICKED_VINDALOO_MENU_ITEM_ID = "1";
public static final String RESTAURANT_NAME = "My Restaurant";

private final int revisedQuantityOfChickenVindaloo = 10;
private String host = System.getenv("DOCKER_HOST_IP");
private int consumerId;
Expand Down Expand Up @@ -225,7 +229,7 @@ private void verifyAccountCreatedForConsumer(int consumerId) {
private int createRestaurant() {
Integer restaurantId =
given().
body(new CreateRestaurantRequest("My Restaurant",
body(new CreateRestaurantRequest(RESTAURANT_NAME,
new RestaurantMenu(Collections.singletonList(new MenuItem(CHICKED_VINDALOO_MENU_ITEM_ID, "Chicken Vindaloo", priceOfChickenVindaloo))))).
contentType("application/json").
when().
Expand Down Expand Up @@ -294,6 +298,7 @@ private void verifyOrderHistoryUpdated(int orderId, int consumerId) {
get(orderHistoryBaseUrl() + "?consumerId=" + consumerId).
then().
statusCode(200)
.body("orders[0].restaurantName", equalTo(RESTAURANT_NAME))
.extract().
path("orders[0].status"); // TODO state?
assertNotNull(state);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,8 @@ public DomainEventHandlers domainEventHandlers() {
}

private Optional<SourceEvent> makeSourceEvent(DomainEventEnvelope<?> dee) {
Message message = dee.getMessage();
return Optional.of(new SourceEvent(dee.getAggregateType(), dee
.getAggregateId
(), dee.getEventId()));
return Optional.of(new SourceEvent(dee.getAggregateType(),
dee.getAggregateId(), dee.getEventId()));
}

public void handleOrderCreated(DomainEventEnvelope<OrderCreatedEvent> dee) {
Expand All @@ -59,7 +57,7 @@ private Order makeOrder(String orderId, OrderCreatedEvent event) {
OrderState.APPROVAL_PENDING,
event.getOrderDetails().getLineItems(),
event.getOrderDetails().getOrderTotal(),
"name-of-" + event.getOrderDetails().getRestaurantId());
event.getRestaurantName());
}

public void handleDeliveryPickedUp(DomainEventEnvelope<DeliveryPickedUp>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import org.springframework.context.annotation.Import;

@Configuration
@Import({OrderHistoryDynamoDBConfiguration.class, CommonConfiguration.class})
@Import(CommonConfiguration.class)
public class OrderHistoryServiceMessagingConfiguration {

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
public class GetOrderResponse {
private String orderId;
private OrderState status;
private String restaurantName;


private GetOrderResponse() {
Expand All @@ -18,9 +19,10 @@ public void setStatus(OrderState status) {
this.status = status;
}

public GetOrderResponse(String orderId, OrderState status) {
public GetOrderResponse(String orderId, OrderState status, String restaurantName) {
this.orderId = orderId;
this.status = status;
this.restaurantName = restaurantName;
}

public String getOrderId() {
Expand All @@ -31,4 +33,11 @@ public void setOrderId(String orderId) {
this.orderId = orderId;
}

public String getRestaurantName() {
return restaurantName;
}

public void setRestaurantName(String restaurantName) {
this.restaurantName = restaurantName;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import net.chrisrichardson.ftgo.cqrs.orderhistory.OrderHistory;
import net.chrisrichardson.ftgo.cqrs.orderhistory.OrderHistoryDao;
import net.chrisrichardson.ftgo.cqrs.orderhistory.OrderHistoryFilter;
import net.chrisrichardson.ftgo.cqrs.orderhistory.dynamodb.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -18,21 +19,28 @@
@RequestMapping(path = "/orders")
public class OrderHistoryController {

@Autowired
private OrderHistoryDao orderHistoryDao;

public OrderHistoryController(OrderHistoryDao orderHistoryDao) {
this.orderHistoryDao = orderHistoryDao;
}

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<GetOrdersResponse> getOrders(@RequestParam(name = "consumerId") String consumerId) {
OrderHistory orderHistory = orderHistoryDao.findOrderHistory(consumerId, new OrderHistoryFilter());
return new ResponseEntity<>(new GetOrdersResponse(orderHistory.getOrders()
.stream()
.map(order -> new GetOrderResponse(order.getOrderId(), order.getStatus())).collect(toList()), orderHistory.getStartKey().orElse(null)), HttpStatus.OK);
.map(this::makeGetOrderResponse).collect(toList()), orderHistory.getStartKey().orElse(null)), HttpStatus.OK);
}

private GetOrderResponse makeGetOrderResponse(Order order) {
return new GetOrderResponse(order.getOrderId(), order.getStatus(), order.getRestaurantName());
}

@RequestMapping(path = "/{orderId}", method = RequestMethod.GET)
public ResponseEntity<GetOrderResponse> getOrder(@PathVariable String orderId) {
return orderHistoryDao.findOrder(orderId)
.map(o -> new ResponseEntity<>(new GetOrderResponse(orderId, o.getStatus()), HttpStatus.OK))
.map(order -> new ResponseEntity<>(makeGetOrderResponse(order), HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ public class OrderHistoryDaoDynamoDbTest {
public void setup() {
consumerId = "consumerId" + System.currentTimeMillis();
orderId = "orderId" + System.currentTimeMillis();
System.out.println("orderId=" + orderId);
restaurantName = "Ajanta" + System.currentTimeMillis();
chickenVindaloo = "Chicken Vindaloo" + System.currentTimeMillis();
;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package net.chrisrichardson.ftgo.cqrs.orderhistory.web;

import io.eventuate.javaclient.commonimpl.JSonMapper;
import net.chrisrichardson.ftgo.common.CommonJsonMapperInitializer;
import net.chrisrichardson.ftgo.cqrs.orderhistory.OrderHistoryDao;
import net.chrisrichardson.ftgo.cqrs.orderhistory.dynamodb.Order;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder;

import java.util.Optional;

import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class OrderHistoryControllerTest {

private OrderHistoryDao orderHistoryDao;
private OrderHistoryController orderHistoryController;

@Before
public void setUp() {
orderHistoryDao = mock(OrderHistoryDao.class);
orderHistoryController = new OrderHistoryController(orderHistoryDao);
}

@Test
public void testGetOrder() {
when(orderHistoryDao.findOrder("1")).thenReturn(Optional.of(new Order("1", null, null, null, null, "Ajanta")));

given().
standaloneSetup(configureControllers(orderHistoryController)).
when().
get("/orders/1").
then().
statusCode(200).
body("restaurantName", equalTo("Ajanta"))
;

}

// TODO move to test library

private StandaloneMockMvcBuilder configureControllers(Object... controllers) {
CommonJsonMapperInitializer.registerMoneyModule();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(JSonMapper.objectMapper);
return MockMvcBuilders.standaloneSetup(controllers).setMessageConverters(converter);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
import io.eventuate.tram.springcloudcontractsupport.EventuateContractVerifierConfiguration;
import net.chrisrichardson.ftgo.cqrs.orderhistory.OrderHistoryDao;
import net.chrisrichardson.ftgo.cqrs.orderhistory.dynamodb.Order;
import net.chrisrichardson.ftgo.cqrs.orderhistory.dynamodb.SourceEvent;
import net.chrisrichardson.ftgo.cqrs.orderhistory.messaging.OrderHistoryServiceMessagingConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -24,6 +26,7 @@
import java.util.Optional;

import static io.eventuate.util.test.async.Eventually.eventually;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
Expand Down Expand Up @@ -69,7 +72,14 @@ public void shouldHandleOrderCreatedEvent() throws InterruptedException {
stubFinder.trigger("orderCreatedEvent");

eventually(() -> {
verify(orderHistoryDao).addOrder(any(Order.class), any(Optional.class));
ArgumentCaptor<Order> orderArg = ArgumentCaptor.forClass(Order.class);
ArgumentCaptor<Optional<SourceEvent>> sourceEventArg = ArgumentCaptor.forClass(Optional.class);
verify(orderHistoryDao).addOrder(orderArg.capture(), sourceEventArg.capture());

Order order = orderArg.getValue();
Optional<SourceEvent> sourceEvent = sourceEventArg.getValue();

assertEquals("Ajanta", order.getRestaurantName());
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,31 @@

public class OrderCreatedEvent implements OrderDomainEvent {
private OrderDetails orderDetails;
private String restaurantName;

private OrderCreatedEvent() {
}

public void setOrderDetails(OrderDetails orderDetails) {
public OrderCreatedEvent(OrderDetails orderDetails, String restaurantName) {

this.orderDetails = orderDetails;
this.restaurantName = restaurantName;
}

public OrderCreatedEvent(OrderDetails orderDetails) {
public OrderDetails getOrderDetails() {
return orderDetails;
}

public void setOrderDetails(OrderDetails orderDetails) {
this.orderDetails = orderDetails;
}

public OrderDetails getOrderDetails() {
return orderDetails;
public String getRestaurantName() {
return restaurantName;
}

public void setRestaurantName(String restaurantName) {
this.restaurantName = restaurantName;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ org.springframework.cloud.contract.spec.Contract.make {

outputMessage {
sentTo('net.chrisrichardson.ftgo.orderservice.domain.Order')
body('''{"orderDetails":{"lineItems":[{"quantity":5,"menuItemId":"1","name":"Chicken Vindaloo","price":"12.34","total":"61.70"}],"orderTotal":"61.70","restaurantId":1, "consumerId":1511300065921}}''')
body('''{"orderDetails":{"lineItems":[{"quantity":5,"menuItemId":"1","name":"Chicken Vindaloo","price":"12.34","total":"61.70"}],"orderTotal":"61.70","restaurantId":1, "consumerId":1511300065921}, "restaurantName" : "Ajanta"}''')
headers {
header('event-aggregate-type', 'net.chrisrichardson.ftgo.orderservice.domain.Order')
header('event-type', 'net.chrisrichardson.ftgo.orderservice.api.events.OrderCreatedEvent')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import static net.chrisrichardson.ftgo.orderservice.OrderDetailsMother.CHICKEN_VINDALOO_ORDER;
import static net.chrisrichardson.ftgo.orderservice.OrderDetailsMother.CHICKEN_VINDALOO_ORDER_DETAILS;
import static net.chrisrichardson.ftgo.orderservice.RestaurantMother.AJANTA_RESTAURANT_NAME;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MessagingBase.TestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.NONE)
Expand Down Expand Up @@ -50,7 +51,7 @@ public OrderDomainEventPublisher orderAggregateEventPublisher(DomainEventPublish

protected void orderCreated() {
orderAggregateEventPublisher.publish(CHICKEN_VINDALOO_ORDER,
Collections.singletonList(new OrderCreatedEvent(CHICKEN_VINDALOO_ORDER_DETAILS)));
Collections.singletonList(new OrderCreatedEvent(CHICKEN_VINDALOO_ORDER_DETAILS, AJANTA_RESTAURANT_NAME)));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package net.chrisrichardson.ftgo.orderservice.domain;

public class InvalidMenuItemIdException extends RuntimeException {
public InvalidMenuItemIdException(String menuItemId) {
super("Invalid menu item id " + menuItemId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@
public class Order {

public static ResultWithDomainEvents<Order, OrderDomainEvent>
createOrder(long consumerId, long restaurantId, List<OrderLineItem> orderLineItems) {
Order order = new Order(consumerId, restaurantId, orderLineItems);
createOrder(long consumerId, Restaurant restaurant, List<OrderLineItem> orderLineItems) {
Order order = new Order(consumerId, restaurant.getId(), orderLineItems);
List<OrderDomainEvent> events = singletonList(new OrderCreatedEvent(
new OrderDetails(consumerId, restaurantId, orderLineItems,
order.getOrderTotal())));
new OrderDetails(consumerId, restaurant.getId(), orderLineItems,
order.getOrderTotal()),
restaurant.getName()));
return new ResultWithDomainEvents<>(order, events);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public Order createOrder(long consumerId, long restaurantId,
List<OrderLineItem> orderLineItems = makeOrderLineItems(lineItems, restaurant);

ResultWithDomainEvents<Order, OrderDomainEvent> orderAndEvents =
Order.createOrder(consumerId, restaurantId, orderLineItems);
Order.createOrder(consumerId, restaurant, orderLineItems);

Order order = orderAndEvents.result;
orderRepository.save(order);
Expand All @@ -80,7 +80,7 @@ public Order createOrder(long consumerId, long restaurantId,

private List<OrderLineItem> makeOrderLineItems(List<MenuItemIdAndQuantity> lineItems, Restaurant restaurant) {
return lineItems.stream().map(li -> {
MenuItem om = restaurant.findMenuItem(li.getMenuItemId()).orElseThrow(() -> new RuntimeException("MenuItem not found: " + li.getMenuItemId()));
MenuItem om = restaurant.findMenuItem(li.getMenuItemId()).orElseThrow(() -> new InvalidMenuItemIdException(li.getMenuItemId()));
return new OrderLineItem(li.getMenuItemId(), om.getName(), om.getPrice(), li.getQuantity());
}).collect(toList());
}
Expand Down Expand Up @@ -158,8 +158,8 @@ public void confirmRevision(long orderId, OrderRevision revision) {
updateOrder(orderId, order -> order.confirmRevision(revision));
}

public void createMenu(long id, RestaurantMenu menu) {
Restaurant restaurant = new Restaurant(id, menu.getMenuItems());
public void createMenu(long id, String name, RestaurantMenu menu) {
Restaurant restaurant = new Restaurant(id, name, menu.getMenuItems());
restaurantRepository.save(restaurant);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ public class Restaurant {
@ElementCollection
@CollectionTable(name = "order_service_restaurant_menu_items")
private List<MenuItem> menuItems;
private String name;

private Restaurant() {
}

public Restaurant(long id, List<MenuItem> menuItems) {
public Restaurant(long id, String name, List<MenuItem> menuItems) {
this.id = id;
this.name = name;
this.menuItems = menuItems;
}

Expand All @@ -56,4 +58,8 @@ public Optional<MenuItem> findMenuItem(String menuItemId) {
public List<MenuItem> getMenuItems() {
return menuItems;
}

public String getName() {
return name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ private void createMenu(DomainEventEnvelope<RestaurantCreated> de) {
String restaurantIds = de.getAggregateId();
long id = Long.parseLong(restaurantIds);
RestaurantMenu menu = de.getEvent().getMenu();
orderService.createMenu(id, menu);
orderService.createMenu(id, de.getEvent().getName(), menu);
}

public void reviseMenu(DomainEventEnvelope<RestaurantMenuRevised> de) {
Expand Down
Loading

0 comments on commit 87938c4

Please sign in to comment.