forked from madvirus/ddd-start2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PlaceOrderService.java
54 lines (45 loc) · 2.29 KB
/
PlaceOrderService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.myshop.order.command.application;
import com.myshop.catalog.command.domain.product.Product;
import com.myshop.catalog.command.domain.product.ProductId;
import com.myshop.catalog.command.domain.product.ProductRepository;
import com.myshop.common.ValidationError;
import com.myshop.common.ValidationErrorException;
import com.myshop.order.command.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class PlaceOrderService {
private ProductRepository productRepository;
private OrderRepository orderRepository;
private OrdererService ordererService;
public PlaceOrderService(ProductRepository productRepository,
OrderRepository orderRepository,
OrdererService ordererService) {
this.productRepository = productRepository;
this.orderRepository = orderRepository;
this.ordererService = ordererService;
}
@Transactional
public OrderNo placeOrder(OrderRequest orderRequest) {
List<ValidationError> errors = validateOrderRequest(orderRequest);
// 응용 서비스가 입력 오류를 하나의 익셉션으로 모아서 발생
if (!errors.isEmpty()) throw new ValidationErrorException(errors);
List<OrderLine> orderLines = new ArrayList<>();
for (OrderProduct op : orderRequest.getOrderProducts()) {
Optional<Product> productOpt = productRepository.findById(new ProductId(op.getProductId()));
Product product = productOpt.orElseThrow(() -> new NoOrderProductException(op.getProductId()));
orderLines.add(new OrderLine(product.getId(), product.getPrice(), op.getQuantity()));
}
OrderNo orderNo = orderRepository.nextOrderNo();
Orderer orderer = ordererService.createOrderer(orderRequest.getOrdererMemberId());
Order order = new Order(orderNo, orderer, orderLines, orderRequest.getShippingInfo(), OrderState.PAYMENT_WAITING);
orderRepository.save(order);
return orderNo;
}
private List<ValidationError> validateOrderRequest(OrderRequest orderRequest) {
return new OrderRequestValidator().validate(orderRequest);
}
}