Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.nexters.gotggam.consent.controller;

import com.nexters.gotggam.consent.dto.ConsentDocumentResponse;
import com.nexters.gotggam.consent.service.ConsentService;
import com.nexters.gotggam.global.payload.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "Consent API", description = "약관 API")
@RestController
@RequestMapping("/api/v1/consent-documents")
@RequiredArgsConstructor
public class ConsentController {

private final ConsentService consentService;

@Operation(summary = "최신 약관 조회", description = "약관 유형별 최신 버전의 본문(마크다운)과 버전을 한 건씩 반환한다.")
@GetMapping
public ApiResponse<List<ConsentDocumentResponse>> getLatestDocuments() {
List<ConsentDocumentResponse> responses = consentService.getLatestDocuments();
return ApiResponse.success(responses);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.nexters.gotggam.consent.dto;

import com.nexters.gotggam.consent.entity.ConsentDocument;
import com.nexters.gotggam.consent.entity.ConsentType;
import io.swagger.v3.oas.annotations.media.Schema;

public record ConsentDocumentResponse(

@Schema(description = "약관 유형", example = "PRIVACY_POLICY", requiredMode = Schema.RequiredMode.REQUIRED)
ConsentType type,

@Schema(
description = "약관 버전. 결과 제출 시 consents[].version에 그대로 전달한다.",
example = "v1.0.0",
requiredMode = Schema.RequiredMode.REQUIRED
)
String version,

@Schema(description = "약관 본문 (마크다운)", example = "# 개인정보 처리방침\n...", requiredMode = Schema.RequiredMode.REQUIRED)
String content
) {

public static ConsentDocumentResponse from(ConsentDocument document) {
return new ConsentDocumentResponse(document.getType(), document.getVersion(), document.getContent());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public record ConsentRequest(
@Schema(description = "동의 문서 유형", example = "PRIVACY_POLICY")
@NotNull ConsentType type,

@Schema(description = "동의 문서 버전", example = "v1.0.0")
@Schema(description = "동의 문서 버전. 약관 조회 API가 내려준 version 값을 그대로 전달한다.", example = "v1.0.0")
@NotBlank @Size(max = 20) String version,

@Schema(description = "동의 여부", example = "true", requiredMode = Schema.RequiredMode.REQUIRED)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,32 @@ public class ConsentDocument {
@Column(nullable = false, length = 30)
private ConsentType type;

// 현재 v1.0.0 형식. 시행일(날짜) 형식으로 바뀔 수 있음 - 팀 합의 필요
@Column(nullable = false, length = 20)
private String version;

@Column(columnDefinition = "TEXT")
@Column(nullable = false, columnDefinition = "TEXT")
private String content;

// 유형별로 지금 내려줄 문서 한 건만 true. 지난 버전도 동의 근거로 남겨야 하므로 지우지 않고 끈다
@Column(name = "is_active", nullable = false)
private boolean active;

@CreatedDate
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;

@Builder
private ConsentDocument(ConsentType type, String version, String content) {
private ConsentDocument(
ConsentType type,
String version,
String content,
boolean active
) {
this.type = type;
this.version = version;
this.content = content;
this.active = active;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public enum ConsentErrorCode implements BaseError {

CONSENT_REQUIRED(HttpStatus.BAD_REQUEST, "CONSENT_001", "필수 동의 항목에 동의해야 합니다."),
INCOMPLETE_CONSENT(HttpStatus.BAD_REQUEST, "CONSENT_002", "모든 동의 항목을 제출해야 합니다."),
CONSENT_DOCUMENT_NOT_FOUND(HttpStatus.NOT_FOUND, "CONSENT_003", "약관 문서를 찾을 수 없습니다."),
;

private final HttpStatus httpStatus;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.nexters.gotggam.consent.repository;

import com.nexters.gotggam.consent.entity.ConsentDocument;
import com.nexters.gotggam.consent.entity.ConsentType;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ConsentDocumentRepository extends JpaRepository<ConsentDocument, Long> {

Optional<ConsentDocument> findByTypeAndActiveTrue(ConsentType type);
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package com.nexters.gotggam.consent.service;

import com.nexters.gotggam.consent.dto.ConsentDocumentResponse;
import com.nexters.gotggam.consent.dto.ConsentRequest;
import com.nexters.gotggam.consent.entity.Consent;
import com.nexters.gotggam.consent.entity.ConsentType;
import com.nexters.gotggam.consent.exception.ConsentErrorCode;
import com.nexters.gotggam.consent.repository.ConsentDocumentRepository;
import com.nexters.gotggam.consent.repository.ConsentRepository;
import com.nexters.gotggam.global.exception.BusinessException;
import com.nexters.gotggam.result.entity.Result;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
Expand All @@ -26,6 +29,7 @@ public class ConsentService {
);

private final ConsentRepository consentRepository;
private final ConsentDocumentRepository consentDocumentRepository;

public void validateAgreed(List<ConsentRequest> consents) {
// 1. 필수 동의 유형이 중복/누락 없이 정확히 한 번씩 왔는지 검증
Expand Down Expand Up @@ -55,4 +59,13 @@ public void recordConsents(Result result, List<ConsentRequest> consents, LocalDa
.toList();
consentRepository.saveAll(savedConsents);
}

@Transactional(readOnly = true)
public List<ConsentDocumentResponse> getLatestDocuments() {
return Arrays.stream(ConsentType.values())
.map(type -> consentDocumentRepository.findByTypeAndActiveTrue(type)
.orElseThrow(() -> new BusinessException(ConsentErrorCode.CONSENT_DOCUMENT_NOT_FOUND)))
.map(ConsentDocumentResponse::from)
.toList();
}
Comment on lines +62 to +70

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ConsentDocument에 isActive(또는 active) boolean 컬럼을 추가한 후, 해당 컬럼을 기준으로 판별하는 방향은 어떨까요?

단순히 findFirstByTypeOrderByIdDesc로 "최신 = id 최댓값"을 판단하는 방식은 과거 버전으로 롤백하거나, 수동으로 활성 버전을 지정해야 하는 케이스 등에서 대응이 꼬이는 이슈가 발생할 수 있을 것 같아요 ..!

활성화 여부 컬럼 추가와 함께

  • 활성 문서 교체 로직(새 문서 활성화 + 기존 문서 비활성화를 같은 트랜잭션에서 처리)
  • DB에서 type당 is_active=true가 최대 1건이도록 보장하는 partial unique index
    를 적용하여 도입하는 방향성이 좀 더 적절하다고 생각합니다!

기현님 의견도 여쭤봅니당 ~~

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋은 의견 같습니다!
id 방식은 롤백하려면 새 버전 행을 지워야 해서, 그 버전에 동의한 본문 근거가 사라지는 문제는 놓쳤네요ㅠㅠ
반영해뒀습니다~

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반영 감사합니다 ~!

배포 후에 dev, prod DB에 partial unique index 설정해주시면 좋을 것 같아요!
지금 active 교체를 DB에서 직접 하다보니, 실수로 active 문서를 2건 이상 등록하는 상황을 막기 위해 제약을 걸어둬야 할 것 같습니당

CREATE UNIQUE INDEX uk_consent_document_active_type                                    
      ON consent_document (type)                                                         
      WHERE is_active = true;

이런 수동 DDL이 앞으로도 종종 생길 것 같아서, 추후에 마이그레이션 도구 도입도 같이 얘기해보면 좋을 것 같아요 ㅎㅎ

고생하셨습니다 ~~

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋습니다!!

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.nexters.gotggam.consent.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.nexters.gotggam.TestcontainersConfiguration;
import com.nexters.gotggam.consent.entity.ConsentDocument;
import com.nexters.gotggam.consent.entity.ConsentType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

@Import(TestcontainersConfiguration.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
class ConsentControllerTest {

@Autowired
private MockMvc mockMvc;

@PersistenceContext
private EntityManager em;

@Test
@DisplayName("약관 유형별로 활성 문서 한 건씩을 enum 순서대로 반환하고 비활성 문서는 제외한다")
void getLatestDocuments() throws Exception {
persist(document(ConsentType.TERMS_OF_SERVICE, "v1.0.0", "# 이용약관 v1.0.0", true));
persist(document(ConsentType.PRIVACY_POLICY, "v1.0.0", "# 처리방침 v1.0.0", true));
persist(document(ConsentType.PRIVACY_POLICY, "v1.1.0", "# 처리방침 v1.1.0", false));

em.flush();
em.clear();

mockMvc.perform(get("/api/v1/consent-documents"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.length()").value(2))
.andExpect(jsonPath("$.data[0].type").value("PRIVACY_POLICY"))
.andExpect(jsonPath("$.data[0].version").value("v1.0.0"))
.andExpect(jsonPath("$.data[0].content").value("# 처리방침 v1.0.0"))
.andExpect(jsonPath("$.data[1].type").value("TERMS_OF_SERVICE"))
.andExpect(jsonPath("$.data[1].version").value("v1.0.0"))
.andExpect(jsonPath("$.data[1].content").value("# 이용약관 v1.0.0"));
}

@Test
@DisplayName("약관 유형 중 하나라도 활성 문서가 없으면 404를 반환한다")
void getLatestDocumentsWhenNoActive() throws Exception {
persist(document(ConsentType.PRIVACY_POLICY, "v1.0.0", "# 처리방침 v1.0.0", true));
persist(document(ConsentType.TERMS_OF_SERVICE, "v1.0.0", "# 이용약관 v1.0.0", false));

em.flush();
em.clear();

mockMvc.perform(get("/api/v1/consent-documents"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error.code").value("CONSENT_003"));
}

private <T> T persist(T entity) {
em.persist(entity);
return entity;
}

private ConsentDocument document(ConsentType type, String version, String content, boolean active) {
return ConsentDocument.builder()
.type(type)
.version(version)
.content(content)
.active(active)
.build();
}
}
Loading