|
| 1 | +package com.baeldung.ddd.layers.domain; |
| 2 | + |
| 3 | +import com.baeldung.ddd.layers.domain.exception.DomainException; |
| 4 | +import org.bson.types.ObjectId; |
| 5 | + |
| 6 | +import java.math.BigDecimal; |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.Collections; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +public class Order { |
| 12 | + private final ObjectId id; |
| 13 | + private OrderStatus status; |
| 14 | + private List<Product> products; |
| 15 | + private BigDecimal price; |
| 16 | + |
| 17 | + public Order(final ObjectId id, final List<Product> products) { |
| 18 | + this.id = id; |
| 19 | + this.products = new ArrayList<>(products); |
| 20 | + this.status = OrderStatus.CREATED; |
| 21 | + this.price = products |
| 22 | + .stream() |
| 23 | + .map(Product::getPrice) |
| 24 | + .reduce(BigDecimal.ZERO, BigDecimal::add); |
| 25 | + } |
| 26 | + |
| 27 | + public void complete() { |
| 28 | + validateState(); |
| 29 | + this.status = OrderStatus.COMPLETED; |
| 30 | + } |
| 31 | + |
| 32 | + public void addProduct(final Product product) { |
| 33 | + validateState(); |
| 34 | + validateProduct(product); |
| 35 | + products.add(product); |
| 36 | + price = price.add(product.getPrice()); |
| 37 | + } |
| 38 | + |
| 39 | + public void removeProduct(final String name) { |
| 40 | + validateState(); |
| 41 | + final Product product = getProduct(name); |
| 42 | + products.remove(product); |
| 43 | + |
| 44 | + price = price.subtract(product.getPrice()); |
| 45 | + } |
| 46 | + |
| 47 | + private Product getProduct(String name) { |
| 48 | + return products |
| 49 | + .stream() |
| 50 | + .filter(product -> product |
| 51 | + .getName() |
| 52 | + .equals(name)) |
| 53 | + .findFirst() |
| 54 | + .orElseThrow(() -> new DomainException("Product with " + name + " doesn't exist.")); |
| 55 | + } |
| 56 | + |
| 57 | + private void validateState() { |
| 58 | + if (OrderStatus.COMPLETED.equals(status)) { |
| 59 | + throw new DomainException("The order is in completed state."); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private void validateProduct(final Product product) { |
| 64 | + if (product == null) { |
| 65 | + throw new DomainException("The product cannot be null."); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public ObjectId getId() { |
| 70 | + return id; |
| 71 | + } |
| 72 | + |
| 73 | + public OrderStatus getStatus() { |
| 74 | + return status; |
| 75 | + } |
| 76 | + |
| 77 | + public List<Product> getProducts() { |
| 78 | + return Collections.unmodifiableList(products); |
| 79 | + } |
| 80 | + |
| 81 | + public BigDecimal getPrice() { |
| 82 | + return price; |
| 83 | + } |
| 84 | +} |
0 commit comments