Skip to content

Commit

Permalink
feature: soft delete (#156)
Browse files Browse the repository at this point in the history
* feature: Add soft delete

* feature: Social login disconnect

* fix: Exclude Apple social login disconnect

* fix: Change error code

* refactor: Inline address deletion

Co-authored-by: Chanhyeok Seo <[email protected]>

---------

Co-authored-by: Chanhyeok Seo <[email protected]>
  • Loading branch information
sky980221 and mushroom1324 authored Sep 17, 2024
1 parent de24189 commit 6cfb02b
Show file tree
Hide file tree
Showing 12 changed files with 195 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand Down Expand Up @@ -36,8 +37,9 @@ public class Payment extends BaseEntity {
@Embedded
private Address address;

private LocalDateTime deletedAt;
@Builder
public Payment(Long userId, PaymentStatus paymentStatus, String iamportUid, String merchantUid, BigDecimal amount, String userName, String phoneNumber, Address address) {
public Payment(Long userId, PaymentStatus paymentStatus, String iamportUid, String merchantUid, BigDecimal amount, String userName, String phoneNumber, Address address, LocalDateTime deletedAt) {
this.userId = userId;
this.paymentStatus = paymentStatus;
this.iamportUid = iamportUid;
Expand All @@ -46,6 +48,7 @@ public Payment(Long userId, PaymentStatus paymentStatus, String iamportUid, Stri
this.userName = userName;
this.phoneNumber = phoneNumber;
this.address = address;
this.deletedAt = deletedAt;
}

public static Payment of(Long userId, String merchantUid, BigDecimal amount, String userName, String phoneNumber, Address address) {
Expand All @@ -59,6 +62,13 @@ public static Payment of(Long userId, String merchantUid, BigDecimal amount, Str
.address(address)
.build();
}
public void setDeletedAt(LocalDateTime deletedAt) {
this.deletedAt = deletedAt;
}

public void deleteAddress() {
this.address = null;
}

public void updatePaymentStatus(PaymentStatus paymentStatus) {
this.paymentStatus = paymentStatus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
import com.example.repick.domain.product.entity.Payment;
import org.springframework.data.jpa.repository.JpaRepository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public interface PaymentRepository extends JpaRepository<Payment, Long> {
Optional<Payment> findByIamportUid(String iamportUid);

Optional<Payment> findByMerchantUid(String merchantUid);

List<Payment> findAllByUserId(Long userId);

List<Payment> findAllByDeletedAtBefore(LocalDateTime dateTime);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@
import com.example.repick.domain.clothingSales.entity.ClothingSalesStateType;
import com.example.repick.domain.clothingSales.repository.ClothingSalesRepository;
import com.example.repick.domain.clothingSales.repository.ClothingSalesStateRepository;
import com.example.repick.domain.product.entity.Product;
import com.example.repick.domain.product.entity.ProductOrder;
import com.example.repick.domain.product.entity.ProductOrderState;
import com.example.repick.domain.product.entity.ProductStateType;
import com.example.repick.domain.product.entity.*;
import com.example.repick.domain.product.repository.PaymentRepository;
import com.example.repick.domain.product.repository.ProductOrderRepository;
import com.example.repick.domain.product.repository.ProductRepository;
import com.example.repick.domain.product.service.ProductOrderService;
import com.example.repick.domain.product.service.ProductService;
import com.example.repick.domain.user.entity.User;
import com.example.repick.domain.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
Expand All @@ -33,6 +34,8 @@ public class ProductScheduler {
private final ClothingSalesRepository clothingSalesRepository;
private final ClothingSalesStateRepository clothingSalesStateRepository;
private final AdminService adminService;
private final PaymentRepository paymentRepository;
private final UserRepository userRepository;

@Scheduled(cron = "0 0 0 * * *")
public void updateProductDiscountRate() {
Expand Down Expand Up @@ -93,4 +96,23 @@ public void updateDeliveryTrackerWebhook() {

productOrders.forEach(po -> adminService.enableTracking(po.getTrackingNumber(), carrierId, callbackUrl));
}

@Scheduled(cron = "0 0 0 * * *")
public void deleteAddressAfterThirtyDays() {
LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
paymentRepository.findAllByDeletedAtBefore(thirtyDaysAgo)
.forEach(payment -> {
//결제 λ‚΄μ—­μ—μ„œ 결제 μ •λ³΄λ§Œ 30일 뒀에 μ‚­μ œ
payment.deleteAddress();
paymentRepository.save(payment);
});
}

// 5λ…„ ν›„ 결제 정보 전체 μ‚­μ œν•˜λŠ” μŠ€μΌ€μ€„λŸ¬
@Scheduled(cron = "0 0 0 * * *")
public void deletePaymentAfterFiveYears() {
LocalDateTime fiveYearsAgo = LocalDateTime.now().minusYears(5);
List<Payment> paymentsToDelete = paymentRepository.findAllByDeletedAtBefore(fiveYearsAgo);
paymentRepository.deleteAll(paymentsToDelete);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Optional;

import java.nio.charset.StandardCharsets;


@Tag(name = "User", description = "μœ μ € κ΄€λ ¨ API")
Expand Down Expand Up @@ -216,6 +214,23 @@ public SuccessResponse<Boolean> deleteUser() {
return SuccessResponse.success(userService.deleteUser());
}

@Operation(summary = "νšŒμ› νƒˆν‡΄ν•˜κΈ°",
description = """
νšŒμ› νƒˆν‡΄ 절차λ₯Ό μ§„ν–‰ν•˜κ³ , μ†Œμ…œλ‘œκ·ΈμΈ 연결을 λŠμŠ΅λ‹ˆλ‹€.
**거래 및 결제 기둝과 κ΄€λ ¨λœ 정보(이름, μ—°λ½μ²˜ λ“±)은 5λ…„κ°„ λ³΄κ΄€ν•©λ‹ˆλ‹€.**
**κ·Έ μ™Έμ˜ μ •λ³΄λŠ” 30일 ν›„ μ‚­μ œν•©λ‹ˆλ‹€.**
""")
@DeleteMapping("/withdraw")
public SuccessResponse<Boolean> withdraw(@RequestParam(required = false) Optional<String> accessToken) {
userService.withdraw(accessToken);
return SuccessResponse.success(true);
}



@Operation(summary = "SMS 인증번호 μš”μ²­ν•˜κΈ°",
description = """
SMS 인증번호λ₯Ό μš”μ²­ν•©λ‹ˆλ‹€.
Expand Down
10 changes: 8 additions & 2 deletions src/main/java/com/example/repick/domain/user/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.joda.time.DateTime;

import java.time.LocalDateTime;

Expand All @@ -27,7 +28,7 @@ public class User extends BaseEntity {
private String phoneNumber;
private String profileImage;
private String password;

private LocalDateTime deletedAt;
// μΆ”κ°€ 정보
private String nickname;
@Embedded
Expand Down Expand Up @@ -56,7 +57,7 @@ public class User extends BaseEntity {
private Role role;

@Builder
public User(Long id, OAuthProvider oAuthProvider, String providerId, String email, String nickname, String phoneNumber, Address defaultAddress, Account defaultAccount, String topSize, String bottomSize, String profileImage, String password, Role role, Boolean pushAllow, String fcmToken, Gender gender ) {
public User(Long id, OAuthProvider oAuthProvider, String providerId, String email, String nickname, String phoneNumber, Address defaultAddress, Account defaultAccount, String topSize, String bottomSize, String profileImage, String password, Role role, Boolean pushAllow, String fcmToken, Gender gender,LocalDateTime deletedAt ) {
this.id = id;
this.oAuthProvider = oAuthProvider;
this.providerId = providerId;
Expand All @@ -75,6 +76,7 @@ public User(Long id, OAuthProvider oAuthProvider, String providerId, String emai
this.fcmToken = fcmToken;
this.userClass = UserClass.ROOKIE_COLLECTOR;
this.gender = gender;
this.deletedAt = deletedAt;
}


Expand All @@ -88,6 +90,7 @@ public void update(PatchUserInfo patchUserInfo) {
this.pushAllow = patchUserInfo.pushAllow() != null ? patchUserInfo.pushAllow() : this.pushAllow;
this.fcmToken = patchUserInfo.fcmToken() != null ? patchUserInfo.fcmToken() : this.fcmToken;
this.gender = patchUserInfo.gender() != null ? patchUserInfo.gender() : this.gender;

}

public void updateProfile(String profile) {
Expand All @@ -102,6 +105,9 @@ public void updateClass(UserClass userClass) {
this.userClass = userClass;
}

public void setDeletedAt(LocalDateTime deletedAt) {
this.deletedAt = deletedAt;
}
public void addSettlement(long settlement) {
this.settlement += settlement;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import com.example.repick.domain.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.time.LocalDateTime;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long>, UserRepositoryCustom {

Optional<User> findByProviderId(String providerId);

List<User> findAllByDeletedAtBefore(LocalDateTime thirtyDaysAgo);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.example.repick.domain.user.scheduler;

import com.example.repick.domain.product.entity.Payment;
import com.example.repick.domain.product.repository.PaymentRepository;
import com.example.repick.domain.user.entity.User;
import com.example.repick.domain.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class UserScheduler {

private final UserRepository userRepository;
private final PaymentRepository paymentRepository;

// 맀일 μžμ •μ— μ‹€ν–‰λ˜λŠ” μŠ€μΌ€μ€„λŸ¬
@Scheduled(cron = "0 0 0 * * *")
public void deleteSoftDeletedUsers() {
// 30일이 μ§€λ‚œ μ†Œν”„νŠΈ μ‚­μ œλœ μ‚¬μš©μž 쑰회
LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
List<User> usersToDelete = userRepository.findAllByDeletedAtBefore(thirtyDaysAgo);

userRepository.deleteAll(usersToDelete);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import com.example.repick.domain.product.repository.ProductOrderRepository;
import com.example.repick.domain.user.dto.*;
import com.example.repick.domain.user.entity.User;
import com.example.repick.domain.product.entity.Payment;
import com.example.repick.domain.product.repository.PaymentRepository;
import com.example.repick.domain.user.entity.UserSmsVerificationInfo;
import com.example.repick.domain.user.repository.UserRepository;
import com.example.repick.dynamodb.UserFcmTokenInfoRepository;
Expand All @@ -17,6 +19,10 @@
import com.example.repick.global.jwt.TokenResponse;
import com.example.repick.global.jwt.TokenService;
import com.example.repick.global.jwt.UserDetailsImpl;
import com.example.repick.global.oauth.AppleUserService;
import com.example.repick.global.oauth.GoogleUserService;
import com.example.repick.global.oauth.KakaoUserService;
import com.example.repick.global.oauth.NaverUserService;
import com.example.repick.global.sms.MessageService;
import com.example.repick.global.util.StringParser;
import lombok.RequiredArgsConstructor;
Expand All @@ -25,6 +31,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.Optional;

import java.time.LocalDateTime;
import java.time.ZoneId;
Expand All @@ -44,7 +51,11 @@ public class UserService {
private final TokenService tokenService;
private final ProductOrderRepository productOrderRepository;
private final UserPreferenceRepository userPreferenceRepository;

private final PaymentRepository paymentRepository;
private final NaverUserService naverUserService;
private final KakaoUserService kakaoUserService;
private final AppleUserService appleUserService;
private final GoogleUserService googleUserService;

public GetUserInfo getUserInfo() {
User user = userRepository.findByProviderId(SecurityContextHolder.getContext().getAuthentication().getName())
Expand All @@ -56,7 +67,7 @@ public GetUserInfo getUserInfo() {

public Boolean patchUserInfo(PatchUserInfo patchUserInfo) {
User user = userRepository.findByProviderId(SecurityContextHolder.getContext().getAuthentication().getName())
.orElseThrow(() -> new UsernameNotFoundException("μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."));
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

user.update(patchUserInfo);

Expand All @@ -72,7 +83,7 @@ public Boolean registerProfile(MultipartFile profileImage) {
String email = SecurityContextHolder.getContext().getAuthentication().getName();

User user = userRepository.findByProviderId(email)
.orElseThrow(() -> new UsernameNotFoundException("μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."));
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

String profile = s3UploadService.saveFile(profileImage, "profile/" + user.getId().toString());

Expand All @@ -89,7 +100,7 @@ public Boolean deleteUser() {
String email = SecurityContextHolder.getContext().getAuthentication().getName();

User user = userRepository.findByProviderId(email)
.orElseThrow(() -> new UsernameNotFoundException("μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."));
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

// delete fcm token from ddb
userFcmTokenInfoRepository.deleteById(user.getId());
Expand All @@ -101,10 +112,52 @@ public Boolean deleteUser() {
return true;
}

@Transactional
public Boolean withdraw(Optional<String> accessToken) {
String email = SecurityContextHolder.getContext().getAuthentication().getName();

User user = userRepository.findByProviderId(email)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

// μ†Œμ…œ 둜그인 μ—°κ²° ν•΄μ œ 둜직
switch (user.getOAuthProvider()) {
case KAKAO:
accessToken.ifPresent(kakaoUserService::disconnectKakao);
break;
case NAVER:
accessToken.ifPresent(naverUserService::disconnectNaver);
break;
case GOOGLE:
accessToken.ifPresent(googleUserService::disconnectGoogle);
break;
case APPLE:
break;
default:
throw new CustomException(ErrorCode.INVALID_REQUEST_ERROR);
}
if (user.getDeletedAt() == null) {
user.setDeletedAt(LocalDateTime.now());
user.setIsDeleted();
userRepository.save(user);
}

List<Payment> payments = paymentRepository.findAllByUserId(user.getId());
payments.forEach(payment -> {
if (payment.getDeletedAt() == null) {
payment.setDeletedAt(LocalDateTime.now());
payment.setIsDeleted();
paymentRepository.save(payment);
}
});

return true;
}


@Transactional
public Boolean initSmsVerification(PostInitSmsVerification postInitSmsVerification) {
User user = userRepository.findByProviderId(SecurityContextHolder.getContext().getAuthentication().getName())
.orElseThrow(() -> new UsernameNotFoundException("μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."));
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

String phoneNumber = StringParser.parsePhoneNumber(postInitSmsVerification.phoneNumber());
String randomNumber = messageService.sendSMS(postInitSmsVerification.phoneNumber());
Expand All @@ -124,7 +177,7 @@ public Boolean initSmsVerification(PostInitSmsVerification postInitSmsVerificati
@Transactional
public Boolean verifySmsVerification(PostVerifySmsVerification postVerifySmsVerification) {
User user = userRepository.findByProviderId(SecurityContextHolder.getContext().getAuthentication().getName())
.orElseThrow(() -> new UsernameNotFoundException("μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."));
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

String phoneNumber = StringParser.parsePhoneNumber(postVerifySmsVerification.phoneNumber());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ public class BaseEntity {
public void delete() {
this.isDeleted = true;
}

public void setIsDeleted() {this.isDeleted = true;}
}
Loading

0 comments on commit 6cfb02b

Please sign in to comment.