|
| 1 | +package com.loopers.domain.coupon; |
| 2 | + |
| 3 | +import com.loopers.domain.common.vo.Money; |
| 4 | +import com.loopers.domain.coupon.enums.DiscountType; |
| 5 | +import com.loopers.support.error.CoreException; |
| 6 | +import com.loopers.support.error.ErrorType; |
| 7 | +import jakarta.persistence.*; |
| 8 | +import lombok.AccessLevel; |
| 9 | +import lombok.Getter; |
| 10 | +import lombok.NoArgsConstructor; |
| 11 | + |
| 12 | +import java.math.BigDecimal; |
| 13 | + |
| 14 | +@Entity |
| 15 | +@Table(name = "coupons") |
| 16 | +@Getter |
| 17 | +@NoArgsConstructor(access = AccessLevel.PROTECTED) |
| 18 | +public class Coupon { |
| 19 | + |
| 20 | + @Id |
| 21 | + @GeneratedValue(strategy = GenerationType.IDENTITY) |
| 22 | + private Long id; |
| 23 | + |
| 24 | + @Column(nullable = false) |
| 25 | + private String name; |
| 26 | + |
| 27 | + @Enumerated(EnumType.STRING) |
| 28 | + @Column(nullable = false) |
| 29 | + private DiscountType discountType; |
| 30 | + |
| 31 | + @Column(nullable = false) |
| 32 | + private BigDecimal discountValue; |
| 33 | + |
| 34 | + private Coupon(String name, DiscountType discountType, BigDecimal discountValue) { |
| 35 | + validate(name, discountType, discountValue); |
| 36 | + this.name = name; |
| 37 | + this.discountType = discountType; |
| 38 | + this.discountValue = discountValue; |
| 39 | + } |
| 40 | + |
| 41 | + public static Coupon createFixedCoupon(String name, BigDecimal discountValue) { |
| 42 | + return new Coupon(name, DiscountType.FIXED, discountValue); |
| 43 | + } |
| 44 | + |
| 45 | + public static Coupon createPercentageCoupon(String name, BigDecimal discountValue) { |
| 46 | + return new Coupon(name, DiscountType.PERCENTAGE, discountValue); |
| 47 | + } |
| 48 | + |
| 49 | + public Money calculateDiscount(Money originalPrice) { |
| 50 | + return discountType.calculateDiscount(originalPrice, discountValue); |
| 51 | + } |
| 52 | + |
| 53 | + private void validate(String name, DiscountType discountType, BigDecimal discountValue) { |
| 54 | + if (name == null || name.isBlank()) { |
| 55 | + throw new CoreException(ErrorType.BAD_REQUEST, "쿠폰 이름은 필수입니다."); |
| 56 | + } |
| 57 | + if (discountType == null) { |
| 58 | + throw new CoreException(ErrorType.BAD_REQUEST, "할인 타입은 필수입니다."); |
| 59 | + } |
| 60 | + if (discountValue == null || discountValue.compareTo(BigDecimal.ZERO) <= 0) { |
| 61 | + throw new CoreException(ErrorType.BAD_REQUEST, "할인 값은 0보다 커야 합니다."); |
| 62 | + } |
| 63 | + if (discountType == DiscountType.PERCENTAGE && discountValue.compareTo(BigDecimal.valueOf(100)) > 0) { |
| 64 | + throw new CoreException(ErrorType.BAD_REQUEST, "정률 할인은 100%를 초과할 수 없습니다."); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments