Skip to content

Commit

Permalink
Merge pull request #30 from K-Hackathon-Fledge/27-DeletePost
Browse files Browse the repository at this point in the history
27 delete post
  • Loading branch information
JuseungL authored Aug 8, 2024
2 parents 54acc05 + a2bff7f commit ee80ed4
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public enum ErrorCode {
OVER_SUPPORT_PRICE(BAD_REQUEST, "후원 물품 금액을 초과하였습니다."),
POST_IMAGE_NOT_FOUND(NOT_FOUND, "후원 게시글의 이미지를 찾을 수 없습니다."),
NOT_SUPPORTED_STATUS(BAD_REQUEST, "후원할 수 없는 게시글 상태입니다."),
NOT_DELETED_STATUS(BAD_REQUEST, "삭제할 수 없는 게시글 상태입니다."),

// challenge
CHALLENGE_NOT_FOUND(NOT_FOUND, "챌린지를 찾을 수 없습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public enum SuccessStatus {
GET_SUPPORT_POST_PAGING_SUCCESS(HttpStatus.OK, "후원하기 게시글 페이징 조회 성공"),
GET_DEADLINE_APPROACHING_POST_SUCCESS(HttpStatus.OK, "마감 임박 후원하기 게시글 조회 성공"),
GET_SUPPORT_PROGRESS_SUCCESS(HttpStatus.OK, "후원하기 진행률 조회 성공"),
DELETE_SUPPORT_SUCCESS(HttpStatus.OK, "후원하기 게시글 삭제 성공"),

/**
* canary
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
import com.fledge.fledgeserver.support.service.SupportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.hibernate.annotations.SQLDelete;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

Expand Down Expand Up @@ -41,7 +43,7 @@ public class SupportController {
@PostMapping
public ResponseEntity<ApiResponse<Object>> createSupport(
Principal principal,
@RequestBody PostCreateRequest postCreateRequest
@Valid @RequestBody PostCreateRequest postCreateRequest
) {
Long memberId = SecurityUtils.getCurrentUserId(principal);
supportService.createSupport(memberId, postCreateRequest);
Expand All @@ -55,16 +57,14 @@ public ResponseEntity<ApiResponse<Object>> createSupport(
@PostMapping("/{supportId}/record")
public ResponseEntity<ApiResponse<Object>> createSupportRecord(
@PathVariable(value = "supportId") Long supportId,
@RequestBody RecordCreateRequest donationRequestDto,
@Valid @RequestBody RecordCreateRequest donationRequestDto,
Principal principal
) {
Long memberId = SecurityUtils.getCurrentUserId(principal);
supportService.createSupportRecord(supportId, donationRequestDto, memberId);
return ApiResponse.success(CREATE_DONATE_SUCCESS);
}



@Operation(summary = "후원하기 게시글 수정 시 기존 데이터 조회",
description = "후원하기 게시글의 기존 데이터를 반환합니다.\n" +
"\n" +
Expand All @@ -91,12 +91,21 @@ public ResponseEntity<ApiResponse<PostGetForUpdateResponse>> getSupportForUpdate
public ResponseEntity<ApiResponse<PostGetResponse>> updateSupportPost(
Principal principal,
@PathVariable(value = "supportId") Long supportId,
@RequestBody PostUpdateRequest postUpdateRequest
@Valid @RequestBody PostUpdateRequest postUpdateRequest
) {
Long memberId = SecurityUtils.getCurrentUserId(principal);
supportService.updateSupportPost(memberId, supportId, postUpdateRequest);
return ApiResponse.success(SuccessStatus.UPDATE_SUPPORT_SUCCESS);
}

// TODO :: 후원하기 게시글 삭제 API
@Operation(summary = "후원하기 게시글 삭제", description = "후원하기 게시글을 삭제합니다.")
@DeleteMapping("/{supportId}")
public ResponseEntity<ApiResponse<Object>> deleteSupportPost(
Principal principal,
@PathVariable(value = "supportId") Long supportId
) {
Long memberId = SecurityUtils.getCurrentUserId(principal);
supportService.deleteSupportPost(memberId, supportId);
return ApiResponse.success(SuccessStatus.DELETE_SUPPORT_SUCCESS);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public class PostCreateRequest {
private List<String> images;

@Schema(description = "만료 시점", required = true, example = "2024-12-31")
@NotBlank(message = "만료 시점은 필수입니다.")
@NotNull(message = "만료 시점은 필수입니다.")
@Future(message = "만료 시점은 현재 시간 이후여야 합니다.")
private LocalDate expirationDate;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package com.fledge.fledgeserver.support.dto.request;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Future;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
import jakarta.validation.constraints.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.URL;
Expand Down Expand Up @@ -42,7 +39,7 @@ public class PostUpdateRequest {
private String purchaseUrl;

@Schema(description = "후원 물품 가격", required = true, example = "500000")
@NotBlank(message = "후원 물품 가격은 필수입니다.")
@NotNull(message = "후원 물품 가격은 필수입니다.")
@Positive(message = "가격은 0보다 큰 값이어야 합니다.")
private int price;

Expand All @@ -54,7 +51,7 @@ public class PostUpdateRequest {
private String promise;

@Schema(description = "후원 만료 시점", required = true, example = "2024-12-31")
@NotBlank(message = "만료 시점은 필수입니다.")
@NotNull(message = "만료 시점은 필수입니다.")
@Future(message = "만료 시점은 현재 시간 이후여야 합니다.")
private LocalDate expirationDate;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand All @@ -21,7 +23,9 @@ public class SupportImage {
@ManyToOne
@JoinColumn(name = "support_post_id", nullable = false)
private SupportPost supportPost;


@Column(name = "deleted_at") // 삭제 시각 저장
private LocalDateTime deletedAt;

@Builder
public SupportImage(SupportPost supportPost, String imageUrl) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@
import com.fledge.fledgeserver.support.dto.request.PostUpdateRequest;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLRestriction;
import org.hibernate.annotations.Where;

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

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString
@SQLRestriction("deleted_at IS NULL")
public class SupportPost extends BaseTimeEntity {

@Id
Expand Down Expand Up @@ -89,6 +93,9 @@ public class SupportPost extends BaseTimeEntity {
@Column(nullable = true)
private String zip;

@Column(name = "deleted_at") // 삭제 시각 저장
private LocalDateTime deletedAt;

// TODO :: 챌린지 구현 후 참여 중이거나 완료한 챌린지(뱃지)에 대한 로직 추가

@Builder
Expand Down Expand Up @@ -160,5 +167,9 @@ public void support() {

// 후원 물품 금액 달성 시 후원 완료 처리 "COMPLETED"
public void setCompleted() { this.supportPostStatus = SupportPostStatus.COMPLETED; }

public void softDelete(LocalDateTime deletedAt) {
this.deletedAt = deletedAt;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
Expand Down Expand Up @@ -36,6 +38,9 @@ public class SupportRecord extends BaseTimeEntity {
@Column(nullable = false)
private int amount;

@Column(name = "deleted_at") // 삭제 시각 저장
private LocalDateTime deletedAt;

@Builder
public SupportRecord(Member member, SupportPost supportPost, String account, int amount, String bankName, String bankCode) {
this.member = member;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
import com.fledge.fledgeserver.exception.ErrorCode;
import com.fledge.fledgeserver.support.entity.SupportImage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.webjars.NotFoundException;

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

public interface SupportImageRepository extends JpaRepository<SupportImage, Long> {
Expand All @@ -16,4 +19,9 @@ public interface SupportImageRepository extends JpaRepository<SupportImage, Long
default SupportImage findFirstImageBySupportPostIdOrDefault(Long supportPostId) {
return findFirstImageBySupportPostId(supportPostId).orElse(null);
}

// Soft Delete 시 한방 쿼리 용
@Modifying
@Query("UPDATE SupportImage si SET si.deletedAt = :deletedAt WHERE si.id IN :ids")
void softDeleteByIds(@Param("ids") List<Long> ids, @Param("deletedAt") LocalDateTime deletedAt);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@
import com.fledge.fledgeserver.support.entity.SupportPost;
import com.fledge.fledgeserver.support.entity.SupportRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

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

public interface SupportRecordRepository extends JpaRepository<SupportRecord, Long> {
List<SupportRecord> findAllBySupportPost(SupportPost supportPost);

// null반환
@Query("SELECT COALESCE(SUM(sr.amount), 0) FROM SupportRecord sr WHERE sr.supportPost.id = :supportPostId")
int sumSupportedPriceBySupportPostId(@Param("supportPostId") Long supportPostId);

// Soft Delete 시 한방 쿼리 용
@Modifying
@Query("UPDATE SupportRecord sr SET sr.deletedAt = :deletedAt WHERE sr.id IN :ids")
void softDeleteByIds(@Param("ids") List<Long> ids, @Param("deletedAt") LocalDateTime deletedAt);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.fledge.fledgeserver.support.service;

import com.fledge.fledgeserver.exception.AuthException;
import com.fledge.fledgeserver.exception.CustomException;
import com.fledge.fledgeserver.exception.ErrorCode;
import com.fledge.fledgeserver.file.FileService;
Expand All @@ -22,6 +23,7 @@
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
Expand All @@ -36,7 +38,7 @@ public class SupportService {
private final SupportRecordRepository supportRecordRepository;
private final SupportImageRepository supportImageRepository;
@Lazy
private static final List<SupportPostStatus> unsupportedStatus = Arrays.asList(
private static final List<SupportPostStatus> notPossibleStatus = Arrays.asList(
SupportPostStatus.TERMINATED,
SupportPostStatus.COMPLETED
);
Expand Down Expand Up @@ -103,7 +105,7 @@ record -> record.getMember().getNickname(), // 후원자 닉네임
public void createSupportRecord(Long supportId, RecordCreateRequest recordCreateRequest, Long memberId) {
SupportPost supportPost = supportPostRepository.findSupportByIdOrThrow(supportId); // 게시글

if (unsupportedStatus.contains(supportPost.getSupportPostStatus())) {
if (notPossibleStatus.contains(supportPost.getSupportPostStatus())) {
// "COMPLETED", "TERMINATED" 상태인 경우 후원 불가
throw new CustomException(ErrorCode.NOT_SUPPORTED_STATUS);
}
Expand Down Expand Up @@ -316,4 +318,28 @@ public void checkAndExpireSupportPosts() {
supportPostRepository.save(supportPost);
});
}

@Transactional
public void deleteSupportPost(Long memberId, Long supportId) {
SupportPost supportPost = supportPostRepository.findSupportByIdOrThrow(supportId);
if (!supportPost.getMember().getId().equals(memberId)) {
throw new CustomException(ErrorCode.UNAUTHORIZED_REQUEST);
}
if (notPossibleStatus.contains(supportPost.getSupportPostStatus())) {
throw new CustomException(ErrorCode.NOT_SUPPORTED_STATUS);
}

LocalDateTime now = LocalDateTime.now();

List<Long> imageIds = supportPost.getImages().stream()
.map(SupportImage::getId)
.collect(Collectors.toList());
List<Long> recordIds = supportPost.getSupportRecords().stream()
.map(SupportRecord::getId)
.collect(Collectors.toList());

supportPost.softDelete(now);
supportImageRepository.softDeleteByIds(imageIds, now);
supportRecordRepository.softDeleteByIds(recordIds, now);
}
}

0 comments on commit ee80ed4

Please sign in to comment.