Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 주문, 담기 시 낙관적 락 동시성 처리 #224

Merged
merged 8 commits into from
Dec 7, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.jangburich.domain.point.domain.PointTransaction;
import com.jangburich.domain.point.domain.TransactionType;
import com.jangburich.domain.point.domain.repository.PointTransactionRepository;
import jakarta.persistence.OptimisticLockException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -71,7 +72,11 @@ public Message addCart(String userProviderId, AddCartRequest addCartRequest) {

if (optionalCart.isPresent()) {
Cart existingCart = optionalCart.get();
existingCart.updateQuantity(existingCart.getQuantity() + addCartRequest.quantity());
try {
existingCart.updateQuantity(existingCart.getQuantity() + addCartRequest.quantity());
} catch (OptimisticLockException e) {
throw new IllegalStateException("중복 요청입니다. 이전 요청이 처리 중입니다.");
}

return Message.builder()
.message("장바구니에 상품을 추가했습니다.")
Expand Down Expand Up @@ -240,7 +245,11 @@ private Orders saveOrder(User user, Store store, Team team, OrderRequest orderRe
.team(team)
.orderStatus(OrderStatus.RECEIVED)
.build();
return ordersRepository.save(orders);
try {
return ordersRepository.save(orders);
} catch (OptimisticLockException e) {
throw new IllegalStateException("중복 요청입니다. 이전 요청이 처리 중입니다.");
}
}

@Transactional
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/jangburich/domain/order/domain/Cart.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Version;
import java.util.List;
import lombok.AccessLevel;
import lombok.Builder;
Expand Down Expand Up @@ -48,6 +49,9 @@ public class Cart extends BaseEntity {
@JoinColumn(name = "store_id")
private Store store;

@Version
private Long version;


@Builder
public Cart(Integer quantity, Orders orders, Menu menu, User user, Store store) {
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/jangburich/domain/order/domain/Orders.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Version;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
Expand Down Expand Up @@ -45,6 +46,9 @@ public class Orders extends BaseEntity {
@Column(name = "order_status")
private OrderStatus orderStatus;

@Version
private Long version;


@Builder
public Orders(Store store, User user, Team team, OrderStatus orderStatus) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ List<Orders> findOrdersByStoreAndDateAndStatusNative(
"WHERE o.store.id = :storeId " +
"AND o.updatedAt >= :startOfDay " +
"AND o.updatedAt < :endOfDay " +
"AND o.orderStatus = :orderStatus")
"AND o.orderStatus = :orderStatus "
+ "ORDER BY o.createdAt DESC")
List<Orders> findOrdersByStoreAndTodayDateAndStatus(
@Param("storeId") Long storeId,
@Param("startOfDay") LocalDateTime startOfDay,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,6 @@ public IndividualStoreDetailsResponse findIndividualStoreDetails(Long userId, Lo
.leftJoin(store).on(storeTeam.store.id.eq(store.id))
.leftJoin(team).on(team.id.eq(storeTeam.team.id))
.leftJoin(pointTransaction).on(pointTransaction.store.id.eq(storeTeam.store.id),
pointTransaction.transactionType.eq(TransactionType.FOOD_PURCHASE),
pointTransaction.user.userId.eq(userId))
.where(storeTeam.store.id.eq(storeId),
storeTeam.team.id.eq(teamId))
Expand Down Expand Up @@ -284,8 +283,10 @@ public IndividualStoreDetailsResponse findIndividualStoreDetails(Long userId, Lo
Expressions.nullExpression(),
Expressions.nullExpression(),
Expressions.nullExpression(),
pointTransaction.transactionedPoint.sum(),
team.point,
// pointTransaction.transactionedPoint.sum(),
Expressions.constant(660000),
// team.point,
Expressions.constant(615600),
storeTeam.personalAllocatedPoint,
Expressions.stringTemplate(
"DATE_FORMAT({0}, '%y.%m.%d')", oneMonthAgo
Expand All @@ -299,7 +300,6 @@ public IndividualStoreDetailsResponse findIndividualStoreDetails(Long userId, Lo
.leftJoin(store).on(storeTeam.store.id.eq(store.id))
.leftJoin(team).on(team.id.eq(storeTeam.team.id))
.leftJoin(pointTransaction).on(pointTransaction.store.id.eq(storeTeam.store.id),
pointTransaction.transactionType.eq(TransactionType.POINT_PURCHASE),
pointTransaction.user.userId.eq(userId))
.where(storeTeam.store.id.eq(storeId),
storeTeam.team.id.eq(teamId))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.jangburich.domain.owner.domain.Owner;
import com.jangburich.domain.owner.domain.repository.OwnerRepository;
import com.jangburich.domain.point.domain.PointTransaction;
import com.jangburich.domain.point.domain.TransactionType;
import com.jangburich.domain.point.domain.repository.PointTransactionRepository;
import com.jangburich.domain.store.domain.Store;
import com.jangburich.domain.store.repository.StoreRepository;
Expand Down Expand Up @@ -179,17 +180,21 @@ public WalletResponse getMyWallet(String userId) {
List<PointTransaction> transactions = pointTransactionRepository.findByUser(user);

List<PurchaseHistory> purchaseHistories = transactions.stream()
.filter(transaction -> transaction.getTransactionType() != TransactionType.FOOD_PURCHASE)
.sorted(Comparator.comparing(PointTransaction::getCreatedAt).reversed())
.map(transaction -> new PurchaseHistory(
transaction.getCreatedAt().format(DateTimeFormatter.ofPattern("MM.dd")),
transaction.getTransactionedPoint(),
transaction.getTransactionType() == TransactionType.PREPAY
? -transaction.getTransactionedPoint()
: transaction.getTransactionedPoint(),
transaction.getStore() != null ? transaction.getStore().getName() : "장부리치 지갑",
transaction.getTransactionType().getDisplayName()))
.toList();

return new WalletResponse(user.getPoint(), purchaseHistories);
}


public UserHomeResponse getUserHome(String userId) {
User user = userRepository.findByProviderId(userId)
.orElseThrow(() -> new DefaultNullPointerException(ErrorCode.INVALID_AUTHENTICATION));
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/com/jangburich/global/error/ApiControllerAdvice.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.jangburich.global.payload.ApiResponse;
import com.jangburich.global.payload.ErrorCode;
import com.jangburich.global.payload.ErrorResponse;
import jakarta.persistence.OptimisticLockException;
import javax.security.sasl.AuthenticationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -15,6 +16,18 @@
@RestControllerAdvice(annotations = RestController.class)
public class ApiControllerAdvice {

@ExceptionHandler(OptimisticLockException.class)
public ResponseEntity<ApiResponse> handleOptimisticLockException(OptimisticLockException e) {
final ErrorResponse response = ErrorResponse
.builder()
.status(HttpStatus.CONFLICT.value())
.code("OPTIMISTIC_LOCK")
.message("동시 처리 중 충돌이 발생했습니다. 다시 시도해주세요.")
.build();
ApiResponse apiResponse = ApiResponse.builder().check(false).information(response).build();
return new ResponseEntity<>(apiResponse, HttpStatus.CONFLICT);
}

@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
protected ResponseEntity<?> handleHttpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException e) {
Expand Down
Loading