Skip to content

Commit eaae085

Browse files
authored
feat: 수능 여론 투표 API와 첫 질문들 (#52)
- 로그인 없이 질문마다 한 번 고르는 투표. 회원은 회원 번호, 아니면 손님 쿠키로 한 사람을 구분하고 IP는 저장하지 않는다 - 고른 뒤에만 결과(전국, 10표 이상 모인 시·도별)를 돌려주고, 닫힌 질문은 누구나 결과를 본다 - 결과 집계는 질문마다 5초씩 기억해 수능 당일 저녁처럼 몰릴 때 DB를 지킨다. 방금 넣은 표는 바로 더해 보여 준다 - 운영 콘솔용 목록·만들기·숨기기/마감 API - D-2, D-1, 수능 당일(16:40 KST에 열림), 수능 다음 날 질문 13개를 마이그레이션으로 넣는다
1 parent d416c89 commit eaae085

12 files changed

Lines changed: 974 additions & 1 deletion

File tree

‎src/main/java/com/likelion/chak/alert/MinigameRateLimiter.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ public enum Action {
3030
/** 코스 응답은 한 판에 한두 번 보내고, 학교 공용 와이파이처럼 한 주소에 여럿이 있을 수 있어 넉넉하게 시간당 60건. */
3131
D1_COURSE_RESPONSE(60, 3_600_000L),
3232
/** 한 판에 시작과 끝 두 번만 보내지만 학교 공용 와이파이를 감안해 시간당 120건. */
33-
EXAM_CAREER_RUN(120, 3_600_000L);
33+
EXAM_CAREER_RUN(120, 3_600_000L),
34+
/** 수능 여론 투표. 한 사람이 하루 열 개 안팎을 고르지만 학교·학원 공용 와이파이를 감안해 시간당 300건. */
35+
POLL_VOTE(300, 3_600_000L);
3436

3537
final int limit;
3638
final long windowMs;

‎src/main/java/com/likelion/chak/controller/AdminController.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ public class AdminController {
5959
private final AdminAccessService adminAccessService;
6060
private final com.likelion.chak.service.PromotionInquiryService promotionInquiryService;
6161
private final com.likelion.chak.service.BenefitSubmissionService benefitSubmissionService;
62+
private final com.likelion.chak.service.PollService pollService;
6263

6364
@GetMapping("/ads")
6465
public ResponseEntity<List<AdvertisementResponse>> getAdvertisements(
@@ -215,6 +216,30 @@ public ResponseEntity<AdminAccessResponse> cancelAdminInvite(
215216
return ResponseEntity.ok(adminAccessService.cancelInvite(principal.userId(), inviteId));
216217
}
217218

219+
@GetMapping("/polls")
220+
public ResponseEntity<List<com.likelion.chak.dto.PollDtos.AdminPollSummary>> getPolls(
221+
@AuthenticationPrincipal AuthenticatedUser principal) {
222+
authService.getAdmin(principal.userId());
223+
return ResponseEntity.ok(pollService.adminList(Instant.now()));
224+
}
225+
226+
@PostMapping("/polls")
227+
public ResponseEntity<com.likelion.chak.dto.PollDtos.AdminPollSummary> createPoll(
228+
@AuthenticationPrincipal AuthenticatedUser principal,
229+
@Valid @RequestBody com.likelion.chak.dto.PollDtos.AdminPollRequest request) {
230+
authService.getAdmin(principal.userId());
231+
return ResponseEntity.status(HttpStatus.CREATED).body(pollService.create(request, Instant.now()));
232+
}
233+
234+
@PatchMapping("/polls/{pollId}")
235+
public ResponseEntity<com.likelion.chak.dto.PollDtos.AdminPollSummary> updatePoll(
236+
@AuthenticationPrincipal AuthenticatedUser principal,
237+
@PathVariable Long pollId,
238+
@RequestBody com.likelion.chak.dto.PollDtos.AdminPollUpdate request) {
239+
authService.getAdmin(principal.userId());
240+
return ResponseEntity.ok(pollService.update(pollId, request, Instant.now()));
241+
}
242+
218243
@GetMapping("/promotion-inquiries")
219244
public ResponseEntity<SliceResponse<com.likelion.chak.dto.PromotionDtos.InquiryResponse>> getPromotionInquiries(
220245
@AuthenticationPrincipal AuthenticatedUser principal,
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
package com.likelion.chak.controller;
2+
3+
import com.likelion.chak.alert.MinigameRateLimiter;
4+
import com.likelion.chak.alert.MinigameRateLimiter.Action;
5+
import com.likelion.chak.config.AuthenticatedUser;
6+
import com.likelion.chak.dto.GuestSession;
7+
import com.likelion.chak.dto.PollDtos.PollList;
8+
import com.likelion.chak.dto.PollDtos.PollView;
9+
import com.likelion.chak.dto.PollDtos.VoteRequest;
10+
import com.likelion.chak.exception.CustomException;
11+
import com.likelion.chak.exception.ErrorCode;
12+
import com.likelion.chak.repository.GuestIdentityRepository;
13+
import com.likelion.chak.service.AnalyticsService;
14+
import com.likelion.chak.service.GuestIdentityService;
15+
import com.likelion.chak.service.PollService;
16+
import com.likelion.chak.service.RegionNames;
17+
import jakarta.servlet.http.HttpServletRequest;
18+
import jakarta.validation.Valid;
19+
import lombok.RequiredArgsConstructor;
20+
import org.springframework.beans.factory.annotation.Value;
21+
import org.springframework.http.HttpHeaders;
22+
import org.springframework.http.ResponseCookie;
23+
import org.springframework.http.ResponseEntity;
24+
import org.springframework.security.core.annotation.AuthenticationPrincipal;
25+
import org.springframework.web.bind.annotation.CookieValue;
26+
import org.springframework.web.bind.annotation.GetMapping;
27+
import org.springframework.web.bind.annotation.PathVariable;
28+
import org.springframework.web.bind.annotation.PostMapping;
29+
import org.springframework.web.bind.annotation.RequestBody;
30+
import org.springframework.web.bind.annotation.RequestHeader;
31+
import org.springframework.web.bind.annotation.RequestMapping;
32+
import org.springframework.web.bind.annotation.RestController;
33+
34+
import java.time.Duration;
35+
import java.time.Instant;
36+
37+
/** 수능 여론 투표. 로그인 없이 쓰고, 회원이면 회원 번호로, 아니면 손님 쿠키로 한 사람을 구분한다. */
38+
@RestController
39+
@RequestMapping("/api/public/polls")
40+
@RequiredArgsConstructor
41+
public class PublicPollController {
42+
43+
private final PollService pollService;
44+
private final GuestIdentityService guestIdentityService;
45+
private final GuestIdentityRepository guestIdentityRepository;
46+
private final MinigameRateLimiter rateLimiter;
47+
48+
@Value("${chak.guest-cookie.name}")
49+
private String guestCookieName;
50+
51+
@Value("${chak.guest-cookie.max-age-seconds}")
52+
private long guestCookieMaxAgeSeconds;
53+
54+
@Value("${chak.guest-cookie.secure}")
55+
private boolean guestCookieSecure;
56+
57+
@Value("${chak.guest-cookie.same-site:Lax}")
58+
private String guestCookieSameSite;
59+
60+
@GetMapping
61+
public ResponseEntity<PollList> list(
62+
@AuthenticationPrincipal AuthenticatedUser principal,
63+
@CookieValue(name = "${chak.guest-cookie.name}", required = false) String guestKey) {
64+
String voterKey;
65+
if (principal != null) {
66+
voterKey = "u:" + principal.userId();
67+
} else if (guestKey != null && !guestKey.isBlank()) {
68+
// 목록을 볼 때는 손님을 새로 만들지 않는다. 이미 있는 손님이면 고른 답을 같이 보여 준다.
69+
voterKey = guestIdentityRepository.findByGuestKey(guestKey).map(g -> "g:" + g.getId()).orElse(null);
70+
} else {
71+
voterKey = null;
72+
}
73+
return ResponseEntity.ok(pollService.list(voterKey, Instant.now()));
74+
}
75+
76+
@PostMapping("/{pollId}/votes")
77+
public ResponseEntity<PollView> vote(
78+
@PathVariable long pollId,
79+
@AuthenticationPrincipal AuthenticatedUser principal,
80+
@CookieValue(name = "${chak.guest-cookie.name}", required = false) String guestKey,
81+
@RequestHeader(name = "X-Chak-Geo-Country", required = false) String chakCountry,
82+
@RequestHeader(name = "X-Chak-Geo-Region", required = false) String chakRegion,
83+
@RequestHeader(name = "X-Vercel-IP-Country", required = false) String vercelCountry,
84+
@RequestHeader(name = "X-Vercel-IP-Country-Region", required = false) String vercelRegion,
85+
@Valid @RequestBody VoteRequest request,
86+
HttpServletRequest http) {
87+
String ip = ClientIp.of(http);
88+
if (!rateLimiter.tryAcquire(Action.POLL_VOTE, "ip" + ip)) {
89+
throw new CustomException(ErrorCode.TOO_MANY_VOTES);
90+
}
91+
GuestSession guest = null;
92+
String voterKey;
93+
if (principal != null) {
94+
voterKey = "u:" + principal.userId();
95+
} else {
96+
guest = guestIdentityService.resolveOrCreateLimited(guestKey, ip);
97+
voterKey = "g:" + guest.getGuestIdentity().getId();
98+
}
99+
AnalyticsService.Geo geo = AnalyticsService.Geo.fromHeaders(
100+
firstNonBlank(chakCountry, vercelCountry), firstNonBlank(chakRegion, vercelRegion));
101+
if (geo == null) {
102+
geo = AnalyticsService.Geo.fromHeaders(request.geoCountry(), request.geoRegion());
103+
}
104+
String region = geo == null || !"KR".equals(geo.country()) || geo.region() == null
105+
? null : RegionNames.of(geo.country(), geo.region());
106+
PollView view = pollService.vote(pollId, request.optionId(), voterKey, region, Instant.now());
107+
108+
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
109+
if (guest != null && guest.isCreated()) {
110+
builder.header(HttpHeaders.SET_COOKIE, ResponseCookie.from(guestCookieName, guest.getGuestIdentity().getGuestKey())
111+
.httpOnly(true).secure(guestCookieSecure).sameSite(guestCookieSameSite).path("/")
112+
.maxAge(Duration.ofSeconds(guestCookieMaxAgeSeconds)).build().toString());
113+
}
114+
return builder.body(view);
115+
}
116+
117+
private static String firstNonBlank(String preferred, String fallback) {
118+
return preferred != null && !preferred.isBlank() ? preferred : fallback;
119+
}
120+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.likelion.chak.domain;
2+
3+
import jakarta.persistence.*;
4+
import lombok.AccessLevel;
5+
import lombok.Getter;
6+
import lombok.NoArgsConstructor;
7+
8+
import java.time.Instant;
9+
10+
/** 수능 여론 질문 하나. 읽고 쓰는 일은 {@code PollService}가 SQL로 하고, 이 클래스는 표 모양을 정한다. */
11+
@Getter
12+
@Entity
13+
@Table(name = "polls", indexes = @Index(name = "idx_polls_opens", columnList = "opens_at"),
14+
uniqueConstraints = @UniqueConstraint(name = "uk_polls_slug", columnNames = "slug"))
15+
@NoArgsConstructor(access = AccessLevel.PROTECTED)
16+
public class Poll {
17+
18+
@Id
19+
@GeneratedValue(strategy = GenerationType.IDENTITY)
20+
private Long id;
21+
22+
@Column(nullable = false, length = 60)
23+
private String slug;
24+
25+
@Column(nullable = false, length = 30)
26+
private String tag;
27+
28+
@Column(nullable = false, length = 120)
29+
private String question;
30+
31+
@Column(name = "opens_at", nullable = false)
32+
private Instant opensAt;
33+
34+
@Column(name = "closes_at")
35+
private Instant closesAt;
36+
37+
@Column(name = "sort_order", nullable = false)
38+
private int sortOrder;
39+
40+
@Column(nullable = false)
41+
private boolean hidden;
42+
43+
@Column(name = "created_at", nullable = false)
44+
private Instant createdAt;
45+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.likelion.chak.domain;
2+
3+
import jakarta.persistence.*;
4+
import lombok.AccessLevel;
5+
import lombok.Getter;
6+
import lombok.NoArgsConstructor;
7+
8+
/** 질문 하나의 선택지. */
9+
@Getter
10+
@Entity
11+
@Table(name = "poll_options", indexes = @Index(name = "idx_poll_options_poll", columnList = "poll_id"))
12+
@NoArgsConstructor(access = AccessLevel.PROTECTED)
13+
public class PollOption {
14+
15+
@Id
16+
@GeneratedValue(strategy = GenerationType.IDENTITY)
17+
private Long id;
18+
19+
@ManyToOne(fetch = FetchType.LAZY, optional = false)
20+
@JoinColumn(name = "poll_id", nullable = false)
21+
private Poll poll;
22+
23+
@Column(nullable = false, length = 40)
24+
private String label;
25+
26+
@Column(name = "sort_order", nullable = false)
27+
private int sortOrder;
28+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.likelion.chak.domain;
2+
3+
import jakarta.persistence.*;
4+
import lombok.AccessLevel;
5+
import lombok.Getter;
6+
import lombok.NoArgsConstructor;
7+
8+
import java.time.Instant;
9+
10+
/** 한 사람의 한 표. voter_key는 'u:회원번호' 또는 'g:손님번호'이고, IP는 저장하지 않는다. */
11+
@Getter
12+
@Entity
13+
@Table(name = "poll_votes",
14+
indexes = @Index(name = "idx_poll_votes_poll_option", columnList = "poll_id, option_id"),
15+
uniqueConstraints = @UniqueConstraint(name = "uk_poll_votes_voter", columnNames = {"poll_id", "voter_key"}))
16+
@NoArgsConstructor(access = AccessLevel.PROTECTED)
17+
public class PollVote {
18+
19+
@Id
20+
@GeneratedValue(strategy = GenerationType.IDENTITY)
21+
private Long id;
22+
23+
@ManyToOne(fetch = FetchType.LAZY, optional = false)
24+
@JoinColumn(name = "poll_id", nullable = false)
25+
private Poll poll;
26+
27+
@ManyToOne(fetch = FetchType.LAZY, optional = false)
28+
@JoinColumn(name = "option_id", nullable = false)
29+
private PollOption option;
30+
31+
@Column(name = "voter_key", nullable = false, length = 40)
32+
private String voterKey;
33+
34+
@Column(length = 20)
35+
private String region;
36+
37+
@Column(name = "created_at", nullable = false)
38+
private Instant createdAt;
39+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package com.likelion.chak.dto;
2+
3+
import jakarta.validation.constraints.NotNull;
4+
import jakarta.validation.constraints.Size;
5+
6+
import java.time.Instant;
7+
import java.util.List;
8+
9+
public final class PollDtos {
10+
11+
private PollDtos() {
12+
}
13+
14+
public record OptionView(long id, String label) {
15+
}
16+
17+
/** 지역 하나의 결과. counts는 options와 같은 순서. */
18+
public record RegionResult(String region, long total, List<Long> counts) {
19+
}
20+
21+
/**
22+
* 결과. 투표했거나 닫힌 질문에만 붙는다. counts는 options와 같은 순서.
23+
* regions는 표가 일정 수 이상 모인 지역만, 많은 순서로 담는다.
24+
*/
25+
public record Results(long total, List<Long> counts, List<RegionResult> regions) {
26+
}
27+
28+
/** status: upcoming(곧 열림), open(투표 중), closed(마감). */
29+
public record PollView(
30+
long id,
31+
String slug,
32+
String tag,
33+
String question,
34+
Instant opensAt,
35+
Instant closesAt,
36+
String status,
37+
List<OptionView> options,
38+
Long myOptionId,
39+
String myRegion,
40+
Results results) {
41+
}
42+
43+
public record PollList(Instant now, List<PollView> polls) {
44+
}
45+
46+
public record VoteRequest(
47+
@NotNull Long optionId,
48+
@Size(max = 8) String geoCountry,
49+
@Size(max = 40) String geoRegion) {
50+
}
51+
52+
public record AdminPollRequest(
53+
@NotNull @Size(min = 1, max = 60) String slug,
54+
@NotNull @Size(min = 1, max = 30) String tag,
55+
@NotNull @Size(min = 1, max = 120) String question,
56+
@NotNull @Size(min = 2, max = 6) List<@NotNull @Size(min = 1, max = 40) String> options,
57+
@NotNull Instant opensAt,
58+
Instant closesAt,
59+
Integer sortOrder) {
60+
}
61+
62+
public record AdminPollUpdate(Boolean hidden, Instant opensAt, Instant closesAt, Boolean clearClosesAt) {
63+
}
64+
65+
public record AdminPollSummary(
66+
long id,
67+
String slug,
68+
String tag,
69+
String question,
70+
Instant opensAt,
71+
Instant closesAt,
72+
int sortOrder,
73+
boolean hidden,
74+
String status,
75+
List<OptionView> options,
76+
Results results) {
77+
}
78+
}

‎src/main/java/com/likelion/chak/exception/ErrorCode.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,11 @@ public enum ErrorCode {
7575
INVALID_MINIGAME_ANSWERS(HttpStatus.BAD_REQUEST, "INVALID_MINIGAME_ANSWERS", "제출한 답이 올바르지 않습니다."),
7676
INVALID_MINIGAME_RESULT(HttpStatus.BAD_REQUEST, "INVALID_MINIGAME_RESULT", "게임 결과가 올바르지 않습니다."),
7777
INVALID_D1_COURSE_RESPONSE(HttpStatus.BAD_REQUEST, "INVALID_D1_COURSE_RESPONSE", "코스 응답 형식이 올바르지 않습니다."),
78+
POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POLL_NOT_FOUND", "투표를 찾을 수 없습니다."),
79+
POLL_NOT_OPEN(HttpStatus.CONFLICT, "POLL_NOT_OPEN", "지금은 투표할 수 없는 질문이에요."),
80+
INVALID_POLL_OPTION(HttpStatus.BAD_REQUEST, "INVALID_POLL_OPTION", "선택지가 올바르지 않습니다."),
81+
INVALID_POLL(HttpStatus.BAD_REQUEST, "INVALID_POLL", "질문은 1~120자, 선택지는 2~6개(각 1~40자), 여는 시각이 닫는 시각보다 앞서야 합니다."),
82+
TOO_MANY_VOTES(HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY_VOTES", "투표가 너무 많아요. 잠시 후 다시 시도해주세요."),
7883
INVALID_EXAM_CAREER_RUN(HttpStatus.BAD_REQUEST, "INVALID_EXAM_CAREER_RUN", "커리어 기록 형식이 올바르지 않습니다."),
7984
INVALID_DISPLAY_NAME(HttpStatus.BAD_REQUEST, "INVALID_DISPLAY_NAME", "이름은 한글·영문·숫자·공백·마침표·밑줄·하이픈·괄호로 1~20자여야 합니다."),
8085
INVALID_AVATAR(HttpStatus.BAD_REQUEST, "INVALID_AVATAR", "프로필 사진을 처리할 수 없습니다. JPEG·PNG·WebP 150KB 이하 사진을 올려주세요."),

0 commit comments

Comments
 (0)