diff --git a/week10/code/.gitattributes b/week10/code/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/week10/code/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/week10/code/.gitignore b/week10/code/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/week10/code/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/week10/code/build.gradle b/week10/code/build.gradle new file mode 100644 index 0000000..738886a --- /dev/null +++ b/week10/code/build.gradle @@ -0,0 +1,82 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.5.6' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' +description = 'UMC9th' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + // QueryDSL : OpenFeign + implementation "io.github.openfeign.querydsl:querydsl-jpa:7.0" + implementation "io.github.openfeign.querydsl:querydsl-core:7.0" + annotationProcessor "io.github.openfeign.querydsl:querydsl-apt:7.0:jpa" + annotationProcessor "jakarta.persistence:jakarta.persistence-api" + annotationProcessor "jakarta.annotation:jakarta.annotation-api" + + // Swagger + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.13' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-api:2.8.13' + + // Validation + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // Security + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'org.springframework.security:spring-security-test' + + // Jwt + implementation 'io.jsonwebtoken:jjwt-api:0.12.3' + implementation 'io.jsonwebtoken:jjwt-impl:0.12.3' + implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3' + implementation 'org.springframework.boot:spring-boot-configuration-processor' +} + +tasks.named('test') { + useJUnitPlatform() +} + +// QueryDSL 관련 설정 +// generated/querydsl 폴더 생성 & 삽입 +def querydslDir = layout.buildDirectory.dir("generated/querydsl").get().asFile + +// 소스 세트에 생성 경로 추가 (구체적인 경로 지정) +sourceSets { + main.java.srcDirs += [ querydslDir ] +} + +// 컴파일 시 생성 경로 지정 +tasks.withType(JavaCompile).configureEach { + options.generatedSourceOutputDirectory.set(querydslDir) +} + +// clean 태스크에 생성 폴더 삭제 로직 추가 +clean.doLast { + file(querydslDir).deleteDir() +} \ No newline at end of file diff --git a/week10/code/gradle/wrapper/gradle-wrapper.jar b/week10/code/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/week10/code/gradle/wrapper/gradle-wrapper.jar differ diff --git a/week10/code/gradle/wrapper/gradle-wrapper.properties b/week10/code/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/week10/code/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/week10/code/gradlew b/week10/code/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/week10/code/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/week10/code/gradlew.bat b/week10/code/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/week10/code/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/week10/code/settings.gradle b/week10/code/settings.gradle new file mode 100644 index 0000000..457950e --- /dev/null +++ b/week10/code/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'UMC9th' diff --git a/week10/code/src/main/java/com/example/umc9th/Umc9thApplication.java b/week10/code/src/main/java/com/example/umc9th/Umc9thApplication.java new file mode 100644 index 0000000..bc54005 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/Umc9thApplication.java @@ -0,0 +1,15 @@ +package com.example.umc9th; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class Umc9thApplication { + + public static void main(String[] args) { + SpringApplication.run(Umc9thApplication.class, args); + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/controller/MemberController.java b/week10/code/src/main/java/com/example/umc9th/domain/member/controller/MemberController.java new file mode 100644 index 0000000..efe6248 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/controller/MemberController.java @@ -0,0 +1,95 @@ +package com.example.umc9th.domain.member.controller; + +import com.example.umc9th.domain.member.converter.MemberConverter; +import com.example.umc9th.domain.member.dto.req.MemberReqDTO; +import com.example.umc9th.domain.member.dto.res.MemberResDTO; +import com.example.umc9th.domain.member.exception.code.MemberSuccessCode; +import com.example.umc9th.domain.member.service.MemberService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseCookie; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.time.Duration; +import java.util.Map; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/member") +public class MemberController { + private final MemberService memberService; + + @DeleteMapping("/{memberId}") + public ApiResponse deleteMember(@PathVariable Long memberId) { + memberService.withdraw(memberId); + + MemberResDTO.Delete resultDTO = MemberConverter.toDeleteDTO(memberId); + GeneralSuccessCode code = GeneralSuccessCode.OK; + return ApiResponse.onSuccess(code, resultDTO); + } + + // 회원가입 + @PostMapping("/sign-up") + public ApiResponse signUp(@RequestBody @Valid MemberReqDTO.JoinDTO dto){ + return ApiResponse.onSuccess(MemberSuccessCode.FOUND, memberService.signup(dto)); + } + + // 로그인 + @PostMapping("/login") + public ApiResponse login( + @RequestBody @Valid MemberReqDTO.LoginDTO dto, + HttpServletResponse response + ){ + MemberResDTO.LoginTokenDTO result = memberService.login(dto); + + // AccessToken을 Header에 설정 + response.setHeader("Authorization", "Bearer " + result.accessToken()); + + // RefreshToken을 HttpOnly 쿠키로 설정 + ResponseCookie cookie = ResponseCookie.from("refreshToken", result.refreshToken()) + .httpOnly(true) + .secure(false) // HTTPS만 허용할 경우 true + .path("/") + .maxAge(Duration.ofDays(7)) + .build(); + response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString()); + + return ApiResponse.onSuccess(MemberSuccessCode.FOUND, MemberResDTO.LoginDTO.of(result.member())); + } + + @PostMapping("/refresh") + public ApiResponse refreshToken(HttpServletRequest request, HttpServletResponse response) { + // Cookie에서 refreshToken 조회 + String refreshToken = memberService.getCookieValue(request, "refreshToken"); + + // accessToken 재발급 + MemberResDTO.ReissueDTO token = memberService.reissueToken(refreshToken); + + // AccessToken을 Header에 설정 + response.setHeader("Authorization", "Bearer " + token.accessToken()); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, null); + } + + @PostMapping("/logout") + public ApiResponse logout(HttpServletRequest request, HttpServletResponse response) { + String refreshToken = memberService.getCookieValue(request, "refreshToken"); + memberService.logout(refreshToken); + + ResponseCookie deleteCookie = ResponseCookie.from("refreshToken", "") + .httpOnly(true) + .secure(false) + .path("/") + .maxAge(0) + .build(); + response.addHeader(HttpHeaders.SET_COOKIE, deleteCookie.toString()); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, null); + } + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/converter/MemberConverter.java b/week10/code/src/main/java/com/example/umc9th/domain/member/converter/MemberConverter.java new file mode 100644 index 0000000..5a374ea --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/converter/MemberConverter.java @@ -0,0 +1,45 @@ +package com.example.umc9th.domain.member.converter; + +import com.example.umc9th.domain.member.dto.req.MemberReqDTO; +import com.example.umc9th.domain.member.dto.res.MemberResDTO; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.global.auth.enums.Role; + +public class MemberConverter { + + public static MemberResDTO.Delete toDeleteDTO(Long memeberId){ + return MemberResDTO.Delete.builder() + .memeberId(memeberId) + .build(); + } + + // Entity -> DTO + public static MemberResDTO.JoinDTO toJoinDTO(Member member){ + return MemberResDTO.JoinDTO.builder() + .memberId(member.getId()) + .createAt(member.getCreatedAt()) + .build(); + } + + // DTO -> Entity + public static Member toMember(MemberReqDTO.JoinDTO dto, String password, Role role){ + return Member.builder() + .name(dto.name()) + .email(dto.email()) // 추가된 코드 + .password(password) // 추가된 코드 + .role(role) // 추가된 코드 + .birth(dto.birth()) + .address(dto.address()) + .detailAddress(dto.specAddress()) + .gender(dto.gender()) + .build(); + } + + public static MemberResDTO.LoginDTO toLoginDTO(Member member, String accessToken, String refreshToken) { + return MemberResDTO.LoginDTO.builder() + .memberId(member.getId()) + .accessToken(accessToken) + .refreshToken(refreshToken) + .build(); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/dto/req/MemberReqDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/member/dto/req/MemberReqDTO.java new file mode 100644 index 0000000..598f361 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/dto/req/MemberReqDTO.java @@ -0,0 +1,40 @@ +package com.example.umc9th.domain.member.dto.req; + +import com.example.umc9th.domain.member.enums.Address; +import com.example.umc9th.domain.member.enums.Gender; +import com.example.umc9th.global.annotation.ExistFoods; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.time.LocalDate; +import java.util.List; + +public class MemberReqDTO { + public record JoinDTO( + @NotBlank + String name, + @Email + String email, // 추가된 속성 + @NotBlank + String password, // 추가된 속성 + @NotNull + Gender gender, + @NotNull + LocalDate birth, + @NotNull + Address address, + @NotNull + String specAddress, + @ExistFoods + List preferCategory + ){} + + // 로그인 + public record LoginDTO( + @NotBlank + String email, + @NotBlank + String password + ){} +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/dto/res/MemberResDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/member/dto/res/MemberResDTO.java new file mode 100644 index 0000000..70c555d --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/dto/res/MemberResDTO.java @@ -0,0 +1,62 @@ +package com.example.umc9th.domain.member.dto.res; + +import com.example.umc9th.domain.member.entity.Member; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + +public class MemberResDTO { + + @Getter + @Builder + public static class Delete{ + private Long memeberId; + + } + + @Builder + public record JoinDTO( + Long memberId, + LocalDateTime createAt + ){} + + // 로그인 + @Builder + public record LoginDTO( + Long memberId + ){ + public static LoginDTO of(Member member) { + return LoginDTO.builder() + .memberId(member.getId()) + .build(); + } + } + + @Builder + public record LoginTokenDTO( + Member member, + String accessToken, + String refreshToken + ){ + public static LoginTokenDTO of(Member member, String accessToken, String refreshToken) { + return LoginTokenDTO.builder() + .member(member) + .accessToken(accessToken) + .refreshToken(refreshToken) + .build(); + } + } + + @Builder + public record ReissueDTO( + String accessToken + ){ + public static ReissueDTO of(String accessToken){ + return ReissueDTO.builder() + .accessToken(accessToken) + .build(); + } + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Food.java b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Food.java new file mode 100644 index 0000000..d30739d --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Food.java @@ -0,0 +1,30 @@ +package com.example.umc9th.domain.member.entity; + +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import com.example.umc9th.domain.member.enums.FoodName; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.HashSet; +import java.util.Set; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "food") +public class Food extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="name") + @Enumerated(EnumType.STRING) + @Builder.Default + private FoodName name = FoodName.NONE; + + @OneToMany(mappedBy = "food") + private Set memberFoodList = new HashSet<>(); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Member.java b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Member.java new file mode 100644 index 0000000..3d6eef1 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Member.java @@ -0,0 +1,95 @@ +package com.example.umc9th.domain.member.entity; + +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import com.example.umc9th.domain.member.entity.mapping.MemberTerm; +import com.example.umc9th.domain.member.enums.Address; +import com.example.umc9th.domain.member.enums.Gender; +import com.example.umc9th.domain.member.entity.mapping.MemberMission; +import com.example.umc9th.domain.member.enums.SocialType; +import com.example.umc9th.domain.review.entity.Reply; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.global.auth.enums.Role; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "member") +public class Member extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="name", length = 3) + private String name; + + @Column(name="gender") + @Enumerated(EnumType.STRING) + @Builder.Default + private Gender gender = Gender.NONE; + + @Column(name="birth") + private LocalDate birth; + + @Column(name="password") + private String password; + + @Column(name="address") + @Enumerated(EnumType.STRING) + @Builder.Default + private Address address = Address.NONE; + + @Column(name="detail_address") + private String detailAddress; + + @Column(name="point") + @Builder.Default + private Integer point = 0; + + @Column(name="email", nullable = false, unique = true) + private String email; + + //소셜 로그인 + @Column(unique = true) + private Long socialUid; + + @Enumerated(EnumType.STRING) + private SocialType socialType; + // + + @Column(name="phone_number") + private String phoneNumber; + + @Column(name = "delete_at") + private LocalDateTime deletedAt; + + @Enumerated(EnumType.STRING) + private Role role; + + @OneToMany(mappedBy = "member", orphanRemoval = true) + private Set memberFoodList = new HashSet<>(); + + @OneToMany(mappedBy = "member", orphanRemoval = true) + private Set memberTermList = new HashSet<>(); + + @OneToMany(mappedBy = "member", orphanRemoval = true) + private Set memberMissionList = new HashSet<>(); + + @OneToMany(mappedBy = "member") + private Set memberReviewList = new HashSet<>(); + + @OneToOne(mappedBy = "member", cascade = CascadeType.REMOVE, orphanRemoval = true) + private RefreshToken refreshToken; + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/entity/RefreshToken.java b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/RefreshToken.java new file mode 100644 index 0000000..e792adb --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/RefreshToken.java @@ -0,0 +1,33 @@ +package com.example.umc9th.domain.member.entity; + +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +public class RefreshToken extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id", nullable = false) + private Member member; + + @Column(nullable = false) + private String refreshToken; + + @Column(nullable = false) + private LocalDateTime expiryDate; + + public void update(String refreshToken, LocalDateTime expiryDate) { + this.refreshToken = refreshToken; + this.expiryDate = expiryDate; + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Term.java b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Term.java new file mode 100644 index 0000000..d4ea835 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/Term.java @@ -0,0 +1,30 @@ +package com.example.umc9th.domain.member.entity; + +import com.example.umc9th.domain.member.entity.mapping.MemberTerm; +import com.example.umc9th.domain.member.enums.TermName; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.HashSet; +import java.util.Set; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "term") +public class Term extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="name") + @Enumerated(EnumType.STRING) + @Builder.Default + private TermName name = TermName.NONE; + + @OneToMany(mappedBy = "term") + private Set memberTermList = new HashSet<>(); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberFood.java b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberFood.java new file mode 100644 index 0000000..9617dc8 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberFood.java @@ -0,0 +1,44 @@ +package com.example.umc9th.domain.member.entity.mapping; + +import com.example.umc9th.domain.member.entity.Food; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.Objects; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "member_food") +public class MemberFood extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) + @JoinColumn(name = "food_id") + private Food food; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MemberFood)) return false; + MemberFood that = (MemberFood) o; + return Objects.equals(getMember(), that.getMember()) && + Objects.equals(getFood(), that.getFood()); + } + + @Override + public int hashCode() { + return Objects.hash(getMember(), getFood()); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberMission.java b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberMission.java new file mode 100644 index 0000000..dd77e33 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberMission.java @@ -0,0 +1,48 @@ +package com.example.umc9th.domain.member.entity.mapping; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.Objects; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "member_mission") +public class MemberMission extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="is_completed", nullable = false) + private Boolean isCompleted; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "mission_id") + private Mission mission; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MemberMission)) return false; + MemberMission that = (MemberMission) o; + return Objects.equals(getMember(), that.getMember()) && + Objects.equals(getMission(), that.getMission()); + } + + @Override + public int hashCode() { + return Objects.hash(getMember(), getMission()); + } + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberTerm.java b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberTerm.java new file mode 100644 index 0000000..9944fa5 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberTerm.java @@ -0,0 +1,45 @@ +package com.example.umc9th.domain.member.entity.mapping; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.entity.Term; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.Objects; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "member_term") +public class MemberTerm extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) + @JoinColumn(name = "term_id") + private Term term; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MemberTerm)) return false; + MemberTerm that = (MemberTerm) o; + return Objects.equals(getMember(), that.getMember()) && + Objects.equals(getTerm(), that.getTerm()); + } + + @Override + public int hashCode() { + return Objects.hash(getMember(), getTerm()); + } + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/enums/Address.java b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/Address.java new file mode 100644 index 0000000..c21742d --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/Address.java @@ -0,0 +1,30 @@ +package com.example.umc9th.domain.member.enums; + +public enum Address { + DOBONG, + DONGDAEMUN, + DONGJAK, + EUNPYEONG, + GANGBUK, + GANGDONG, + GANGNAM, + GANGSEO, + GEUMCHEON, + GURO, + GWANAK, + GWANGJIN, + JONGNO, + JUNG, + JUNGNANG, + MAPO, + NOWON, + SEOCHO, + SEODAEMUN, + SEONGBUK, + SEONGDONG, + SONGPA, + YANGCHEON, + YEONGDEUNGPO, + YONGSAN, + NONE; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/enums/FoodName.java b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/FoodName.java new file mode 100644 index 0000000..2bc4dd5 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/FoodName.java @@ -0,0 +1,17 @@ +package com.example.umc9th.domain.member.enums; + +public enum FoodName { + KOREAN, + JAPANESE, + CHINESE, + WESTERN, //양식 + CHICKEN, + SNACK, //분식 + MEAT_GRILL, // '고기/구이'를 의미 + LUNCH_BOX, // 도시락 + NIGHT_SNACK, //야식 + FAST_FOOD, + DESSERT, + ASIAN, + NONE; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/enums/Gender.java b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/Gender.java new file mode 100644 index 0000000..076166f --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/Gender.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.member.enums; + +public enum Gender { + MALE, FEMALE, NONE; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/enums/SocialType.java b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/SocialType.java new file mode 100644 index 0000000..2df39f0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/SocialType.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.member.enums; + +public enum SocialType { + KAKAO +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/enums/TermName.java b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/TermName.java new file mode 100644 index 0000000..8007406 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/enums/TermName.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.member.enums; + +public enum TermName { + AGE, SERVICE, PRIVACY, LOCATION, MARKETING, NONE; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/exception/FoodException.java b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/FoodException.java new file mode 100644 index 0000000..71f7432 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/FoodException.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.member.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; + +public class FoodException extends GeneralException { + public FoodException(BaseErrorCode code) { + super(code); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/exception/MemberException.java b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/MemberException.java new file mode 100644 index 0000000..1e4d7a1 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/MemberException.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.member.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; + +public class MemberException extends GeneralException { + public MemberException(BaseErrorCode code) { + super(code); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/FoodErrorCode.java b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/FoodErrorCode.java new file mode 100644 index 0000000..09591b5 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/FoodErrorCode.java @@ -0,0 +1,16 @@ +package com.example.umc9th.domain.member.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum FoodErrorCode implements BaseErrorCode { + NOT_FOUND(HttpStatus.BAD_REQUEST, "FOOD400_1", "존재하지 않는 음식입니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/MemberErrorCode.java b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/MemberErrorCode.java new file mode 100644 index 0000000..f1df8f0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/MemberErrorCode.java @@ -0,0 +1,22 @@ +package com.example.umc9th.domain.member.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum MemberErrorCode implements BaseErrorCode { + + MEMBER_NOT_FOUND(HttpStatus.BAD_REQUEST, "MEMBER400_1", "존재하지 않는 회원입니다."), + INVALID(HttpStatus.BAD_REQUEST, "MEMBER400_2", "유효하지 않은 정보"), + TOKEN_INVALID(HttpStatus.UNAUTHORIZED, "TOKEN401_1", "유효하지 않은 토큰입니다."), + ; + + + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/MemberSuccessCode.java b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/MemberSuccessCode.java new file mode 100644 index 0000000..5da173c --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/exception/code/MemberSuccessCode.java @@ -0,0 +1,21 @@ +package com.example.umc9th.domain.member.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseSuccessCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum MemberSuccessCode implements BaseSuccessCode { + + FOUND(HttpStatus.OK, + "MEMBER200_1", + "성공적으로 사용자를 조회했습니다."), + + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/repository/FoodRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/FoodRepository.java new file mode 100644 index 0000000..8407493 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/FoodRepository.java @@ -0,0 +1,7 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.Food; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FoodRepository extends JpaRepository { +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberFoodRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberFoodRepository.java new file mode 100644 index 0000000..c66810d --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberFoodRepository.java @@ -0,0 +1,16 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import jakarta.transaction.Transactional; +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; + +public interface MemberFoodRepository extends JpaRepository { + @Transactional + @Modifying(clearAutomatically = true) + @Query("DELETE FROM MemberFood mf WHERE mf.member.id = :memberId") + void deleteAllByMemberIdInBatch(@Param("memberId") Long memberId); + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberMissionRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberMissionRepository.java new file mode 100644 index 0000000..abc42fc --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberMissionRepository.java @@ -0,0 +1,36 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.mapping.MemberMission; +import com.example.umc9th.domain.mission.entity.Mission; +import jakarta.transaction.Transactional; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +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; + +public interface MemberMissionRepository extends JpaRepository { + @Transactional + @Modifying(clearAutomatically = true) + @Query("DELETE FROM MemberMission mm WHERE mm.member.id = :memberId") + void deleteAllByMemberIdInBatch(@Param("memberId") Long memberId); + + //3. 진행 중, 진행 완료 미션 + @Query(value = "SELECT mm FROM MemberMission mm " + + "JOIN FETCH mm.mission m " + + "JOIN FETCH m.store " + + "WHERE mm.member.id = :memberId ", + countQuery = "SELECT count(mm) FROM MemberMission mm WHERE mm.member.id = :memberId") //countQuery 분리(페이징) + Page findMemberMissionsByMemberIdWithDetails(Long memberId, Pageable pageable); + + //4-1. 홈 화면 - 해당 지역 달성 미션 개수 + @Query("SELECT COUNT(mm) FROM MemberMission mm " + + "WHERE mm.member.id = :memberId AND mm.mission.store.location.id = :locationId") + Long countCompletedMissionsInLocation(Long memberId, Long locationId); + + + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberRepository.java new file mode 100644 index 0000000..e5385c1 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberRepository.java @@ -0,0 +1,17 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.Member; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface MemberRepository extends JpaRepository { + + //2. 마이 페이지 + Optional findById(Long memberId); + + Optional findByEmail(String email); + + Optional findBySocialUid(Long socialUid); + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberTermRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberTermRepository.java new file mode 100644 index 0000000..c50ba16 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/MemberTermRepository.java @@ -0,0 +1,15 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.mapping.MemberTerm; +import jakarta.transaction.Transactional; +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; + +public interface MemberTermRepository extends JpaRepository { + @Transactional + @Modifying(clearAutomatically = true) + @Query("DELETE FROM MemberTerm mt WHERE mt.member.id = :memberId") + void deleteAllByMemberIdInBatch(@Param("memberId") Long memberId); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/repository/RefreshTokenRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/RefreshTokenRepository.java new file mode 100644 index 0000000..77edb7c --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/RefreshTokenRepository.java @@ -0,0 +1,14 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.RefreshToken; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface RefreshTokenRepository extends JpaRepository { + Optional findByMemberId(Long id); + + Optional findByRefreshToken(String refreshToken); + + void deleteByRefreshToken(String refreshToken); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/repository/TermRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/TermRepository.java new file mode 100644 index 0000000..41eacc9 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/repository/TermRepository.java @@ -0,0 +1,7 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.Term; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface TermRepository extends JpaRepository { +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/member/service/MemberService.java b/week10/code/src/main/java/com/example/umc9th/domain/member/service/MemberService.java new file mode 100644 index 0000000..05bbaa8 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/member/service/MemberService.java @@ -0,0 +1,210 @@ +package com.example.umc9th.domain.member.service; + +import com.example.umc9th.domain.member.converter.MemberConverter; +import com.example.umc9th.domain.member.dto.req.MemberReqDTO; +import com.example.umc9th.domain.member.dto.res.MemberResDTO; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.entity.RefreshToken; +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import com.example.umc9th.domain.member.exception.FoodException; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.exception.code.FoodErrorCode; +import com.example.umc9th.domain.member.exception.code.MemberErrorCode; +import com.example.umc9th.domain.member.repository.*; +import com.example.umc9th.domain.review.repository.ReplyRepository; +import com.example.umc9th.domain.review.repository.ReviewRepository; +import com.example.umc9th.global.auth.details.CustomUserDetails; +import com.example.umc9th.global.auth.dto.KakaoResDTO; +import com.example.umc9th.global.auth.enums.Role; +import com.example.umc9th.global.auth.token.JwtUtil; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.swing.text.html.Option; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class MemberService { + private final MemberTermRepository memberTermRepository; + private final MemberRepository memberRepository; + private final MemberFoodRepository memberFoodRepository; + private final MemberMissionRepository memberMissionRepository; + private final ReviewRepository reviewRepository; + private final ReplyRepository replyRepository; + private final FoodRepository foodRepository; + private final RefreshTokenRepository refreshTokenRepository; + + private final PasswordEncoder passwordEncoder; + private final JwtUtil jwtUtil; + + @Transactional + public void withdraw(Long memberId) { + if(!memberRepository.existsById(memberId)) { + throw new MemberException(MemberErrorCode.MEMBER_NOT_FOUND); + } + memberTermRepository.deleteAllByMemberIdInBatch(memberId); + memberFoodRepository.deleteAllByMemberIdInBatch(memberId); + memberMissionRepository.deleteAllByMemberIdInBatch(memberId); + + List reviewIds = reviewRepository.findAllIdsByMemberId(memberId); + if(reviewIds == null || reviewIds.isEmpty()) { + replyRepository.deleteAllByReviewIdsInBatch(reviewIds); + reviewRepository.deleteAllByIdsInBatch(reviewIds); + } + memberRepository.deleteById(memberId); + + } + + @Transactional + public MemberResDTO.JoinDTO signup(MemberReqDTO.JoinDTO dto){ + String salt = passwordEncoder.encode(dto.password()); + // 사용자 생성 + Member member = MemberConverter.toMember(dto, salt, Role.ROLE_USER); + // DB 적용 + memberRepository.save(member); + + // 선호 음식 존재 여부 확인 + if (dto.preferCategory().size() > 1){ + List memberFood = dto.preferCategory().stream() + .map(id -> MemberFood.builder() + .member(member) + .food(foodRepository.findById(id) + .orElseThrow(() -> new FoodException(FoodErrorCode.NOT_FOUND))) + .build() + ) + .collect(Collectors.toList()); + + memberFoodRepository.saveAll(memberFood); + } + + + // 응답 DTO 생성 + return MemberConverter.toJoinDTO(member); + } + + @Transactional + public MemberResDTO.LoginTokenDTO login( + MemberReqDTO.@Valid LoginDTO dto + ) { + + // Member 조회 + Member member = memberRepository.findByEmail(dto.email()) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + // 비밀번호 검증 + if (!passwordEncoder.matches(dto.password(), member.getPassword())){ + throw new MemberException(MemberErrorCode.INVALID); + } + + // JWT 토큰 발급용 UserDetails + CustomUserDetails userDetails = new CustomUserDetails(member); + + // 엑세스 토큰 발급 + String accessToken = jwtUtil.createAccessToken(userDetails); + String refreshToken = jwtUtil.createRefreshToken(userDetails); + + saveOrUpdateRefreshToken(member, refreshToken); + + // DTO 조립 + return MemberResDTO.LoginTokenDTO.of(member, accessToken, refreshToken); + } + + @Transactional + public MemberResDTO.LoginTokenDTO loginOrSignup(KakaoResDTO.UserInfoDTO kakaoUserInfo) { + + Long kakaoId = kakaoUserInfo.id(); + String email = kakaoUserInfo.kakaoAccount().email(); + + // 1. DB에서 카카오 ID로 회원 조회, 없으면 새로 생성 + Member member = memberRepository.findBySocialUid(kakaoId) + .orElseGet(() -> { + // 신규 회원가입 + Member newMember = Member.builder() + .socialUid(kakaoId) + .email(email) + .role(Role.ROLE_USER) + .build(); + return memberRepository.save(newMember); + }); + + + // 2. 우리 서비스의 JWT 토큰 발급 + CustomUserDetails userDetails = new CustomUserDetails(member); + String accessToken = jwtUtil.createAccessToken(userDetails); + String refreshToken = jwtUtil.createRefreshToken(userDetails); + + saveOrUpdateRefreshToken(member, refreshToken); + + + + // 3. 결과 반환 + return MemberResDTO.LoginTokenDTO.of(member, accessToken, refreshToken); + } + + + private void saveOrUpdateRefreshToken(Member member, String refreshToken){ + Optional existingTokenEntity = refreshTokenRepository.findByMemberId(member.getId()); + if(existingTokenEntity.isPresent()) { + existingTokenEntity.get().update(refreshToken, LocalDateTime.now().plusDays(7)); + } + else{ + RefreshToken newTokenEntity = RefreshToken.builder() + .member(member) + .refreshToken(refreshToken) + .expiryDate(LocalDateTime.now().plusDays(7)) + .build(); + refreshTokenRepository.save(newTokenEntity); + } + + } + + @Transactional + public void logout(String refreshToken) { + if (refreshToken != null && jwtUtil.isValid(refreshToken)) { + refreshTokenRepository.deleteByRefreshToken(refreshToken); + } + } + + @Transactional + public MemberResDTO.ReissueDTO reissueToken(String refreshToken) { + // 1. 토큰 유효성 검사 (JWT 서명/만료) + if (!jwtUtil.isValid(refreshToken)) { + throw new MemberException(MemberErrorCode.TOKEN_INVALID); + } + + // 2. 토큰 값으로 DB 조회 + RefreshToken savedToken = refreshTokenRepository.findByRefreshToken(refreshToken) + .orElseThrow(() -> new MemberException(MemberErrorCode.TOKEN_INVALID)); + + // 3. Member 조회 + Member member = savedToken.getMember(); + + // 엑세스 토큰 발급 + String accessToken = jwtUtil.createAccessToken(new CustomUserDetails(member)); + + return MemberResDTO.ReissueDTO.of(accessToken); + } + + public String getCookieValue(HttpServletRequest request, String name) { + if (request.getCookies() == null) return null; + for (Cookie cookie : request.getCookies()) { + if (name.equals(cookie.getName())) { + return cookie.getValue(); + } + } + return null; + } + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/controller/MissionController.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/controller/MissionController.java new file mode 100644 index 0000000..70d15e6 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/controller/MissionController.java @@ -0,0 +1,75 @@ +package com.example.umc9th.domain.mission.controller; + + +import com.example.umc9th.domain.mission.dto.req.MissionReqDTO; +import com.example.umc9th.domain.mission.dto.res.MissionResDTO; +import com.example.umc9th.domain.mission.exception.code.MissionSuccessCode; +import com.example.umc9th.domain.mission.service.MissionService; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import com.example.umc9th.global.dto.PageDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.web.bind.annotation.*; + + + +@RestController +@RequiredArgsConstructor +public class MissionController { + private final MissionService missionService; + + // 미션 추가 API + @PostMapping("/missions") + public ApiResponse addMission(@RequestBody @Valid MissionReqDTO.AddDTO dto){ + MissionResDTO.AddDTO result = missionService.addMission(dto); + MissionSuccessCode code = MissionSuccessCode.ADD_OK; + return ApiResponse.onSuccess(code, result); + } + + // 미션 도전 API + @PostMapping("/missions/challenge") + public ApiResponse challengeMission(@RequestBody @Valid MissionReqDTO.ChallengeDTO dto){ + MissionResDTO.ChallengeDTO result = missionService.challengeMission(dto); + MissionSuccessCode code = MissionSuccessCode.CHALLENGE_OK; + return ApiResponse.onSuccess(code, result); + } + + // 특정 가게의 미션 목록 (11.25) + @Operation( + summary = "특정 가게의 미션 목록 조회 API (11.25)", + description = "특정 가게의 미션 목록을 모두 조회합니다. 페이지네이션으로 제공합니다." + ) + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") + }) + @GetMapping("/missions/{storeId}") + public ApiResponse> getMissions(@PathVariable Long storeId, @Valid @ValidPage Pageable pageable){ + PageDTO result = missionService.getMissions(storeId, pageable); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, result); + } + + // 내가 진행중인 미션 목록 (11.25) + @Operation( + summary = "내가 진행중인 미션 목록 조회 API (11.25)", + description = "내가 진행중인 미션 목록을 모두 조회합니다. 페이지네이션으로 제공합니다." + ) + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") + }) + @GetMapping("/missions/{memberId}/me") + public ApiResponse> getMyMissions(@PathVariable Long memberId, @RequestParam Boolean isCompleted, @Valid @ValidPage Pageable pageable){ + PageDTO result = missionService.getMyMissions(memberId, isCompleted, pageable); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, result); + } + + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/converter/MissionConverter.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/converter/MissionConverter.java new file mode 100644 index 0000000..0a11609 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/converter/MissionConverter.java @@ -0,0 +1,42 @@ +package com.example.umc9th.domain.mission.converter; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.entity.mapping.MemberMission; +import com.example.umc9th.domain.mission.dto.req.MissionReqDTO; +import com.example.umc9th.domain.mission.dto.res.MissionResDTO; +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.store.entity.Store; + +public class MissionConverter { + + public static Mission toAddEntity(MissionReqDTO.AddDTO dto, Store store){ + return Mission.builder() + .deadline(dto.deadline()) + .missionCondition(dto.missionCondition()) + .point(dto.point()) + .store(store) + .build(); + } + + public static MissionResDTO.AddDTO toAddDTO(Mission mission){ + return MissionResDTO.AddDTO.builder() + .missionId(mission.getId()) + .createAt(mission.getCreatedAt()) + .build(); + } + + public static MemberMission toChallengeEntity(Mission mission, Member member){ + return MemberMission.builder() + .isCompleted(false) + .mission(mission) + .member(member) + .build(); + } + + public static MissionResDTO.ChallengeDTO toChallengeDTO(MemberMission memberMission){ + return MissionResDTO.ChallengeDTO.builder() + .memberMissionId(memberMission.getId()) + .createAt(memberMission.getCreatedAt()) + .build(); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/dto/req/MissionReqDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/dto/req/MissionReqDTO.java new file mode 100644 index 0000000..7a6a919 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/dto/req/MissionReqDTO.java @@ -0,0 +1,26 @@ +package com.example.umc9th.domain.mission.dto.req; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.time.LocalDate; + +public class MissionReqDTO { + public record AddDTO( + @NotNull + LocalDate deadline, + @NotBlank + String missionCondition, + @NotNull + Integer point, + @NotNull + Long storeId + ){} + + public record ChallengeDTO( + @NotNull + Long memberId, + @NotNull + Long missionId + ){} +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/dto/res/MissionResDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/dto/res/MissionResDTO.java new file mode 100644 index 0000000..305b383 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/dto/res/MissionResDTO.java @@ -0,0 +1,38 @@ +package com.example.umc9th.domain.mission.dto.res; + +import com.example.umc9th.domain.mission.entity.Mission; +import lombok.Builder; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class MissionResDTO { + @Builder + public record AddDTO( + Long missionId, + LocalDateTime createAt + ){} + + @Builder + public record ChallengeDTO( + Long memberMissionId, + LocalDateTime createAt + ){} + + @Builder + public record MissionDTO( + Long missionId, + LocalDate deadline, + String missionCondition, + Integer point + ){ + public static MissionDTO of(Mission mission) { + return MissionDTO.builder() + .missionId(mission.getId()) + .deadline(mission.getDeadline()) + .missionCondition(mission.getMissionCondition()) + .point(mission.getPoint()) + .build(); + } + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/entity/Mission.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/entity/Mission.java new file mode 100644 index 0000000..8c4b06a --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/entity/Mission.java @@ -0,0 +1,52 @@ +package com.example.umc9th.domain.mission.entity; + +import com.example.umc9th.domain.member.entity.mapping.MemberMission; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "mission") +public class Mission extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="deadline", nullable = false) + private LocalDate deadline; + + @Column(name="mission_condition", nullable = false) + private String missionCondition; + + @Column(name="point", nullable = false) + private Integer point; + + @OneToMany(mappedBy = "mission") + private Set memberMissionList = new HashSet<>(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Mission)) return false; + Mission mission = (Mission) o; + return Objects.equals(getStore(), mission.getStore()); + } + @Override + public int hashCode() { + return Objects.hash(getStore()); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/MissionException.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/MissionException.java new file mode 100644 index 0000000..df838a8 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/MissionException.java @@ -0,0 +1,11 @@ +package com.example.umc9th.domain.mission.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; + + +public class MissionException extends GeneralException { + public MissionException(BaseErrorCode code) { + super(code); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionErrorCode.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionErrorCode.java new file mode 100644 index 0000000..20643ad --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionErrorCode.java @@ -0,0 +1,18 @@ +package com.example.umc9th.domain.mission.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum MissionErrorCode implements BaseErrorCode { + + NOT_FOUND(HttpStatus.BAD_REQUEST, "MISSION400_1", "존재하지 않는 미션입니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java new file mode 100644 index 0000000..b29f819 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java @@ -0,0 +1,20 @@ +package com.example.umc9th.domain.mission.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseSuccessCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum MissionSuccessCode implements BaseSuccessCode { + + ADD_OK(HttpStatus.OK, "MISSION200_1", "미션이 정상적으로 추가되었습니다."), + CHALLENGE_OK(HttpStatus.OK, "MISSION200_2", "미션 도전이 정상적으로 처리되었습니다."), + + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/repository/MissionRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/repository/MissionRepository.java new file mode 100644 index 0000000..70bbe92 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/repository/MissionRepository.java @@ -0,0 +1,43 @@ +package com.example.umc9th.domain.mission.repository; + +import com.example.umc9th.domain.mission.entity.Mission; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface MissionRepository extends JpaRepository { + + //4-2. 홈화면 - 도전 가능 미션 목록 + @Query(value = "SELECT m FROM Mission m " + + "JOIN FETCH m.store s " + + "WHERE m.store.location.id = :locationId AND " + + "NOT EXISTS (" + + " SELECT 1 FROM MemberMission mm " + + " WHERE mm.member.id = :memberId AND mm.mission = m" + + ")", + countQuery = "SELECT count(m) FROM Mission m " + //countQuery 분리(페이징) + "WHERE m.store.location.id = :locationId AND " + + "NOT EXISTS (" + + " SELECT 1 FROM MemberMission mm " + + " WHERE mm.member.id = :memberId AND mm.mission = m" + + ")") + Page findAvailableMissions(Long locationId, Long memberId, Pageable pageable); + + Page findByStoreId(Long storeId, Pageable pageable); + + @Query(value = "SELECT m FROM MemberMission mm " + + "JOIN mm.mission m " + // 1. FETCH 제거 (일반 JOIN 사용) + "WHERE mm.member.id = :memberId AND mm.isCompleted = :isCompleted", + + countQuery = "SELECT count(mm) FROM MemberMission mm " + // 2. countQuery 명시 + "WHERE mm.member.id = :memberId AND mm.isCompleted = :isCompleted") + Page findByMemberIdAndIsCompleted(@Param("memberId") Long memberId, + @Param("isCompleted") Boolean isCompleted, + Pageable pageable); + + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/mission/service/MissionService.java b/week10/code/src/main/java/com/example/umc9th/domain/mission/service/MissionService.java new file mode 100644 index 0000000..3160eb3 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/mission/service/MissionService.java @@ -0,0 +1,77 @@ +package com.example.umc9th.domain.mission.service; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.entity.mapping.MemberMission; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.exception.code.MemberErrorCode; +import com.example.umc9th.domain.member.repository.MemberMissionRepository; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.mission.converter.MissionConverter; +import com.example.umc9th.domain.mission.dto.req.MissionReqDTO; +import com.example.umc9th.domain.mission.dto.res.MissionResDTO; +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.mission.exception.MissionException; +import com.example.umc9th.domain.mission.exception.code.MissionErrorCode; +import com.example.umc9th.domain.mission.repository.MissionRepository; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.exception.StoreException; +import com.example.umc9th.domain.store.exception.code.StoreErrorCode; +import com.example.umc9th.domain.store.repository.StoreRepository; +import com.example.umc9th.global.dto.PageDTO; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class MissionService { + private final MissionRepository missionRepository; + private final StoreRepository storeRepository; + private final MemberRepository memberRepository; + private final MemberMissionRepository memberMissionRepository; + + @Transactional + public MissionResDTO.AddDTO addMission(MissionReqDTO.AddDTO dto){ + Store store = storeRepository.findById(dto.storeId()) + .orElseThrow(() -> new StoreException(StoreErrorCode.STORE_NOT_FOUND)); + Mission mission = MissionConverter.toAddEntity(dto, store); + + Mission savedMission = missionRepository.save(mission); + + return MissionConverter.toAddDTO(savedMission); + } + + @Transactional + public MissionResDTO.ChallengeDTO challengeMission(MissionReqDTO.ChallengeDTO dto){ + Mission mission = missionRepository.findById(dto.missionId()) + .orElseThrow(() -> new MissionException(MissionErrorCode.NOT_FOUND)); + Member member = memberRepository.findById(dto.memberId()) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + MemberMission savedMemberMission = memberMissionRepository.save(MissionConverter.toChallengeEntity(mission, member)); + + return MissionConverter.toChallengeDTO(savedMemberMission); + + } + + @Transactional(readOnly = true) + public PageDTO getMissions(Long storeId, Pageable pageable){ + Pageable unsortedPageable = PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()); + Page missions = missionRepository.findByStoreId(storeId, unsortedPageable); + + return PageDTO.of(missions, MissionResDTO.MissionDTO::of); + } + + @Transactional(readOnly = true) + public PageDTO getMyMissions(Long memberId, Boolean isCompleted,Pageable pageable){ + Pageable unsortedPageable = PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()); + Page missions = missionRepository.findByMemberIdAndIsCompleted(memberId, isCompleted, unsortedPageable); + return PageDTO.of(missions, MissionResDTO.MissionDTO::of); + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/controller/ReviewController.java b/week10/code/src/main/java/com/example/umc9th/domain/review/controller/ReviewController.java new file mode 100644 index 0000000..c2fad8c --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/controller/ReviewController.java @@ -0,0 +1,95 @@ +package com.example.umc9th.domain.review.controller; + +import com.example.umc9th.domain.review.converter.ReviewConverter; +import com.example.umc9th.domain.review.dto.req.ReviewReqDTO; +import com.example.umc9th.domain.review.dto.res.ReviewResDTO; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.review.exception.code.ReviewSuccessCode; +import com.example.umc9th.domain.review.service.ReviewQueryService; +import com.example.umc9th.domain.review.service.ReviewService; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import com.example.umc9th.global.dto.PageDTO; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Pageable; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +public class ReviewController { + private final ReviewQueryService reviewQueryService; + private final ReviewService reviewService; + + @GetMapping("/reviews/search") // 리뷰 검색 + public ApiResponse> searchReview(@RequestParam String query, @RequestParam String type) { + List result = reviewQueryService.searchReview(query, type); + + List resultDTO = result.stream().map(ReviewConverter::toSearchDTO).toList(); + GeneralSuccessCode code = GeneralSuccessCode.OK; + + return ApiResponse.onSuccess(code, resultDTO); + } + + @GetMapping("/reviews/members/{memberId}") // 회원 리뷰 검색 + public ApiResponse> memberReviews(@PathVariable String memberId, @RequestParam String query, @RequestParam String type) { + List result = reviewQueryService.memberReviews(Long.parseLong(memberId), query, type); + + List resultDTO = result.stream().map(ReviewConverter::toSearchDTO).toList(); + GeneralSuccessCode code = GeneralSuccessCode.OK; + + return ApiResponse.onSuccess(code, resultDTO); + + } + + // 리뷰 추가 API + @PostMapping("/reviews") + public ApiResponse addReview(@RequestBody ReviewReqDTO.AddDTO dto) { + ReviewResDTO.AddDTO result = reviewService.addReview(dto); + + ReviewSuccessCode code = ReviewSuccessCode.OK; + return ApiResponse.onSuccess(code, result); + } + + // 가게의 리뷰 목록 조회 + @Operation( + summary = "가게의 리뷰 목록 조회 API By 마크 (개발 중)", + description = "특정 가게의 리뷰를 모두 조회합니다. 페이지네이션으로 제공합니다." + ) + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") + }) + @GetMapping("/reviews") + public ApiResponse> getReviews(@RequestParam String storeName, @Valid @ValidPage Pageable pageable) { + + ReviewSuccessCode code = ReviewSuccessCode.FOUND; + return ApiResponse.onSuccess(code, reviewService.findReview(storeName, pageable)); + } + + // 내가 작성한 리뷰 목록 (11.25) + @Operation( + summary = "내가 작성한 리뷰 목록 조회 API (11.25)", + description = "내가 작성한 리뷰를 모두 조회합니다. 페이지네이션으로 제공합니다." + ) + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") + }) + @GetMapping("/reviews/members/{memberId}/me") + public ApiResponse> getMyReviews(@PathVariable Long memberId, @Valid @ValidPage Pageable pageable) { + PageDTO result = reviewService.getMyReviews(memberId, pageable); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, result); + } + + + + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/converter/ReviewConverter.java b/week10/code/src/main/java/com/example/umc9th/domain/review/converter/ReviewConverter.java new file mode 100644 index 0000000..2a62499 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/converter/ReviewConverter.java @@ -0,0 +1,64 @@ +package com.example.umc9th.domain.review.converter; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.review.dto.req.ReviewReqDTO; +import com.example.umc9th.domain.review.dto.res.ReviewResDTO; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.store.entity.Store; +import org.springframework.data.domain.Page; + +import java.time.LocalDate; + +public class ReviewConverter { + + public static ReviewResDTO.Search toSearchDTO(Review review){ + return ReviewResDTO.Search.builder() + .reviewId(review.getId()) + .content(review.getContent()) + .star(review.getStar()) + .memberId(review.getMember().getId()) + .replyId(review.getReply().getId()) + .storeId(review.getStore().getId()) + .build(); + } + + public static Review toAddEntity(ReviewReqDTO.AddDTO dto, Member member, Store store){ + return Review.builder() + .content(dto.content()) + .star(dto.star()) + .member(member) + .store(store) + .build(); + } + + public static ReviewResDTO.AddDTO toAddDTO(Review review){ + return ReviewResDTO.AddDTO.builder() + .reviewId(review.getId()) + .createAt(review.getCreatedAt()) + .build(); + } + + // result -> DTO + public static ReviewResDTO.ReviewPreViewListDTO toReviewPreviewListDTO(Page result){ + return ReviewResDTO.ReviewPreViewListDTO.builder() + .reviewList(result.getContent().stream() + .map(ReviewConverter::toReviewPreviewDTO) + .toList() + ) + .listSize(result.getSize()) + .totalPage(result.getTotalPages()) + .totalElements(result.getTotalElements()) + .isFirst(result.isFirst()) + .isLast(result.isLast()) + .build(); + } + + public static ReviewResDTO.ReviewPreViewDTO toReviewPreviewDTO(Review review){ + return ReviewResDTO.ReviewPreViewDTO.builder() + .ownerNickname(review.getMember().getName()) + .score(review.getStar()) + .body(review.getContent()) + .createdAt(LocalDate.from(review.getCreatedAt())) + .build(); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/dto/req/ReviewReqDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/review/dto/req/ReviewReqDTO.java new file mode 100644 index 0000000..88760e5 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/dto/req/ReviewReqDTO.java @@ -0,0 +1,21 @@ +package com.example.umc9th.domain.review.dto.req; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +public class ReviewReqDTO { + + public record AddDTO( + @NotBlank + @Size(min = 1, max = 1000) + String content, + @NotNull + @Size(min = 1, max = 5) + Float star, + @NotNull + Long memberId, + @NotNull + Long storeId + ){} +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/dto/res/ReviewResDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/review/dto/res/ReviewResDTO.java new file mode 100644 index 0000000..b7fcbd4 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/dto/res/ReviewResDTO.java @@ -0,0 +1,50 @@ +package com.example.umc9th.domain.review.dto.res; + +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +public class ReviewResDTO { + + @Getter + @Builder + public static class Search{ + private Long reviewId; + private String content; + private Float star; + private Long memberId; + private Long storeId; + private Long replyId; + } + + @Builder + public record AddDTO( + Long reviewId, + LocalDateTime createAt + ){} + + @Builder + public record ReviewPreViewListDTO( + List reviewList, + Integer listSize, + Integer totalPage, + Long totalElements, + Boolean isFirst, + Boolean isLast + ){} + + @Builder + public record ReviewPreViewDTO( + String ownerNickname, + Float score, + String body, + LocalDate createdAt + ){} + + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/entity/Reply.java b/week10/code/src/main/java/com/example/umc9th/domain/review/entity/Reply.java new file mode 100644 index 0000000..1df4b7d --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/entity/Reply.java @@ -0,0 +1,25 @@ +package com.example.umc9th.domain.review.entity; + +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "reply") +public class Reply extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "content", nullable = false) + @Lob + private String content; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "review_id") + private Review review; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/entity/Review.java b/week10/code/src/main/java/com/example/umc9th/domain/review/entity/Review.java new file mode 100644 index 0000000..2c25e2b --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/entity/Review.java @@ -0,0 +1,53 @@ +package com.example.umc9th.domain.review.entity; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.Objects; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "review") +public class Review extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "content", nullable = false) + @Lob + private String content; + + @Column(name = "star", nullable = false) + private Float star; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + @OneToOne(mappedBy = "review", cascade = CascadeType.REMOVE, orphanRemoval = true) + private Reply reply; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Review)) return false; + Review review = (Review) o; + return Objects.equals(getMember(), review.getMember()); + } + + @Override + public int hashCode() { + return Objects.hash(getMember()); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/exception/ReviewException.java b/week10/code/src/main/java/com/example/umc9th/domain/review/exception/ReviewException.java new file mode 100644 index 0000000..afde6b0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/exception/ReviewException.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.review.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; + +public class ReviewException extends GeneralException { + public ReviewException(BaseErrorCode code) { + super(code); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewErrorCode.java b/week10/code/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewErrorCode.java new file mode 100644 index 0000000..fa2d3d3 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewErrorCode.java @@ -0,0 +1,20 @@ +package com.example.umc9th.domain.review.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ReviewErrorCode implements BaseErrorCode { + + REVIEW_EXCEPTION(HttpStatus.BAD_REQUEST, "REVIEW400_1", "잘못된 요청"), + NOT_FOUND(HttpStatus.NOT_FOUND, "REVIEW404_1", "해당 리뷰를 찾을 수 없습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewSuccessCode.java b/week10/code/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewSuccessCode.java new file mode 100644 index 0000000..91aded9 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewSuccessCode.java @@ -0,0 +1,20 @@ +package com.example.umc9th.domain.review.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseSuccessCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ReviewSuccessCode implements BaseSuccessCode { + + OK(HttpStatus.OK, "REVIEW200_1", "리뷰가 정상적으로 등록되었습니다."), + FOUND(HttpStatus.OK, "REVIEW200_2", "리뷰가 정상적으로 조회되었습니다.") + + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/repository/ReplyRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/ReplyRepository.java new file mode 100644 index 0000000..3640186 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/ReplyRepository.java @@ -0,0 +1,17 @@ +package com.example.umc9th.domain.review.repository; + +import com.example.umc9th.domain.review.entity.Reply; +import jakarta.transaction.Transactional; +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.util.List; + +public interface ReplyRepository extends JpaRepository { + @Transactional + @Modifying(clearAutomatically = true) + @Query("DELETE FROM Reply rp WHERE rp.review.id IN :reviewIds") + void deleteAllByReviewIdsInBatch(@Param("reviewIds") List reviewIds); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/repository/ReviewRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/ReviewRepository.java new file mode 100644 index 0000000..84a178d --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/ReviewRepository.java @@ -0,0 +1,29 @@ +package com.example.umc9th.domain.review.repository; + +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.review.repository.querydsl.ReviewQueryDSL; +import com.example.umc9th.domain.store.entity.Store; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +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 javax.swing.text.html.Option; +import java.util.List; + +public interface ReviewRepository extends JpaRepository, ReviewQueryDSL { + @Query("SELECT r.id FROM Review r WHERE r.member.id = :memberId") + List findAllIdsByMemberId(@Param("memberId") Long memberId); + + @Modifying(clearAutomatically = true) + @Query("DELETE FROM Review r WHERE r.id IN :reviewIds") + void deleteAllByIdsInBatch(@Param("reviewIds") List reviewIds); + + + Page findAllByStore(Store store, Pageable pageable); + + Page findByMemberId(Long memberId, Pageable pageable); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDSL.java b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDSL.java new file mode 100644 index 0000000..dcb9fba --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDSL.java @@ -0,0 +1,12 @@ +package com.example.umc9th.domain.review.repository.querydsl; + +import com.example.umc9th.domain.review.entity.Review; +import com.querydsl.core.types.Predicate; + +import java.util.List; + + +public interface ReviewQueryDSL { + List searchReview(Predicate predicate); + List memberReviews(Predicate predicate); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDSLImpl.java b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDSLImpl.java new file mode 100644 index 0000000..33f9700 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDSLImpl.java @@ -0,0 +1,56 @@ +package com.example.umc9th.domain.review.repository.querydsl; + +import com.example.umc9th.domain.review.entity.QReview; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.store.entity.QLocation; +import com.example.umc9th.domain.store.entity.QStore; +import com.querydsl.core.types.Predicate; +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; + +import java.util.List; + + + +@Repository +@RequiredArgsConstructor +public class ReviewQueryDSLImpl implements ReviewQueryDSL { + + private final EntityManager em; + + @Override + public List searchReview(Predicate predicate){ + JPAQueryFactory queryFactory = new JPAQueryFactory(em); + + QReview review = QReview.review; + QStore store = QStore.store; + QLocation location = QLocation.location; + + //join on -> fetchJoin 변경 + return queryFactory + .selectFrom(review) + .join(review.store, store).fetchJoin() + .join(store.location, location).fetchJoin() + .where(predicate) + .fetch(); + } + + @Override + public List memberReviews(Predicate predicate){ + JPAQueryFactory queryFactory = new JPAQueryFactory(em); + + QReview review = QReview.review; + QStore store = QStore.store; + + //join on -> fetchJoin 변경 + return queryFactory + .selectFrom(review) + .join(review.store, store).fetchJoin() + .where(predicate) + .fetch(); + + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/service/ReviewQueryService.java b/week10/code/src/main/java/com/example/umc9th/domain/review/service/ReviewQueryService.java new file mode 100644 index 0000000..a22daf6 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/service/ReviewQueryService.java @@ -0,0 +1,93 @@ +package com.example.umc9th.domain.review.service; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.exception.code.MemberErrorCode; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.review.converter.ReviewConverter; +import com.example.umc9th.domain.review.dto.req.ReviewReqDTO; +import com.example.umc9th.domain.review.dto.res.ReviewResDTO; +import com.example.umc9th.domain.review.entity.QReview; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.review.repository.ReviewRepository; +import com.example.umc9th.domain.store.entity.QLocation; +import com.example.umc9th.domain.store.entity.QStore; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.exception.StoreException; +import com.example.umc9th.domain.store.exception.code.StoreErrorCode; +import com.example.umc9th.domain.store.repository.StoreRepository; +import com.querydsl.core.BooleanBuilder; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class ReviewQueryService { + private final ReviewRepository reviewRepository; + private final MemberRepository memberRepository; + private final StoreRepository storeRepository; + + public List searchReview(String query, String type) { + QReview review = QReview.review; + QLocation location = QLocation.location; + BooleanBuilder builder = new BooleanBuilder(); + + if(type.equals("location")){ + builder.and(location.name.contains(query)); + } + if(type.equals("star")){ + builder.and(review.star.goe(Float.parseFloat(query))); + } + if(type.equals("both")){ + String firstQuery = query.split("&")[0]; + String secondQuery = query.split("&")[1]; + + builder.and(location.name.contains(firstQuery)); + builder.and(review.star.goe(Float.parseFloat(secondQuery))); + } + + List reviewList = reviewRepository.searchReview(builder); + return reviewList; + } + + public List memberReviews(Long memberId, String query, String type) { + QReview review = QReview.review; + QStore store = QStore.store; + + BooleanBuilder builder = new BooleanBuilder(); + + if(type.equals("store")){ + builder.and(store.name.eq(query)); + } + if(type.equals("star")){ + builder.and(review.star.goe(Float.parseFloat(query))); // 4.0 <= star < 5.0 + builder.and(review.star.lt(Float.parseFloat(query) + 1.0)); + } + if(type.equals("both")){ //query=송강루&4 + String firstQuery = query.split("&")[0]; + String secondQuery = query.split("&")[1]; + + builder.and(store.name.eq(firstQuery)); + builder.and(review.star.goe(Float.parseFloat(secondQuery))); + builder.and(review.star.lt(Float.parseFloat(secondQuery) + 1.0)); + + } + + builder.and(review.member.id.eq(memberId)); + + List reviewList = reviewRepository.memberReviews(builder); + return reviewList; + } + + + + + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/review/service/ReviewService.java b/week10/code/src/main/java/com/example/umc9th/domain/review/service/ReviewService.java new file mode 100644 index 0000000..0427410 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/review/service/ReviewService.java @@ -0,0 +1,68 @@ +package com.example.umc9th.domain.review.service; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.exception.code.MemberErrorCode; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.review.converter.ReviewConverter; +import com.example.umc9th.domain.review.dto.req.ReviewReqDTO; +import com.example.umc9th.domain.review.dto.res.ReviewResDTO; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.review.repository.ReviewRepository; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.exception.StoreException; +import com.example.umc9th.domain.store.exception.code.StoreErrorCode; +import com.example.umc9th.domain.store.repository.StoreRepository; +import com.example.umc9th.global.dto.PageDTO; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class ReviewService { + private final ReviewRepository reviewRepository; + private final MemberRepository memberRepository; + private final StoreRepository storeRepository; + + @Transactional + public ReviewResDTO.AddDTO addReview(ReviewReqDTO.AddDTO dto) { + Member member = memberRepository.findById(dto.memberId()) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + Store store = storeRepository.findById(dto.storeId()) + .orElseThrow(() -> new StoreException(StoreErrorCode.STORE_NOT_FOUND)); + + Review review = ReviewConverter.toAddEntity(dto, member, store); + + Review savedReview = reviewRepository.save(review); + return ReviewConverter.toAddDTO(savedReview); + } + + @Transactional + public PageDTO findReview(String storeName, Pageable pageable){ + // - 가게를 가져온다 (가게 존재 여부 검증) + Store store = storeRepository.findByName(storeName) + // - 없으면 예외 터뜨린다 + .orElseThrow(() -> new StoreException(StoreErrorCode.STORE_NOT_FOUND)); + + //- 가게에 맞는 리뷰를 가져온다 (Offset 페이징) + Pageable unsortedPageable = PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()); + Page result = reviewRepository.findAllByStore(store, unsortedPageable); + + //- 결과를 응답 DTO로 변환한다 (컨버터 이용) + return PageDTO.of(result, ReviewConverter::toReviewPreviewDTO); + } + + @Transactional(readOnly = true) + public PageDTO getMyReviews(Long memberId, Pageable pageable){ + //sort값 무시 + Pageable unsortedPageable = PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()); + Page reviews = reviewRepository.findByMemberId(memberId, unsortedPageable); + + return PageDTO.of(reviews, ReviewConverter::toReviewPreviewDTO); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/controller/LocationController.java b/week10/code/src/main/java/com/example/umc9th/domain/store/controller/LocationController.java new file mode 100644 index 0000000..6b8952e --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/controller/LocationController.java @@ -0,0 +1,30 @@ +package com.example.umc9th.domain.store.controller; + +import com.example.umc9th.domain.store.converter.LocationConverter; +import com.example.umc9th.domain.store.dto.req.LocationReqDTO; +import com.example.umc9th.domain.store.dto.res.LocationResDTO; +import com.example.umc9th.domain.store.entity.Location; +import com.example.umc9th.domain.store.service.LocationService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +public class LocationController { + + private final LocationService locationService; + + @PostMapping("/locations") + public ApiResponse addLocation(@RequestBody LocationReqDTO request) { + Location result = locationService.addLocation(request); + + LocationResDTO.Add resultDTO = LocationConverter.toAddDTO(result); + GeneralSuccessCode code = GeneralSuccessCode.OK; + + return ApiResponse.onSuccess(code, resultDTO); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/controller/StoreController.java b/week10/code/src/main/java/com/example/umc9th/domain/store/controller/StoreController.java new file mode 100644 index 0000000..c7aefdd --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/controller/StoreController.java @@ -0,0 +1,49 @@ +package com.example.umc9th.domain.store.controller; + +import com.example.umc9th.domain.store.converter.StoreConverter; +import com.example.umc9th.domain.store.dto.req.StoreReqDTO; +import com.example.umc9th.domain.store.dto.res.StoreResDTO; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.service.StoreService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import com.example.umc9th.global.dto.PageDTO; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +public class StoreController { + private final StoreService storeService; + + @GetMapping("/stores/search") + public ApiResponse> searchStore(@RequestParam List region, + @RequestParam String keyword, + @RequestParam String sort, Pageable pageable) { + //요청URL 예시: /stores/search?region=강남구&keyword=민트 초코&sort=name&page=0&size=10 + //다중검색: ?region=강남구®ion=도봉구®ion=영등포구 + Page result = storeService.searchStores(region, keyword, sort, pageable); + + PageDTO resultDTO = PageDTO.of(result, StoreConverter::toSearchDTO); +// StoreConverter.toPageDTO(result); + GeneralSuccessCode code = GeneralSuccessCode.OK; + + return ApiResponse.onSuccess(code, resultDTO); + } + + //가게 추가 API + @PostMapping("/stores") + public ApiResponse addStore(@RequestBody StoreReqDTO request) { + Store result = storeService.addStore(request); + + StoreResDTO.Add resultDTO = StoreConverter.toAddDTO(result); + GeneralSuccessCode code = GeneralSuccessCode.OK; + + return ApiResponse.onSuccess(code, resultDTO); + + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/converter/LocationConverter.java b/week10/code/src/main/java/com/example/umc9th/domain/store/converter/LocationConverter.java new file mode 100644 index 0000000..7b05372 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/converter/LocationConverter.java @@ -0,0 +1,13 @@ +package com.example.umc9th.domain.store.converter; + +import com.example.umc9th.domain.store.dto.res.LocationResDTO; +import com.example.umc9th.domain.store.entity.Location; + +public class LocationConverter { + + public static LocationResDTO.Add toAddDTO(Location location){ + return LocationResDTO.Add.builder() + .locationId(location.getId()) + .build(); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/converter/StoreConverter.java b/week10/code/src/main/java/com/example/umc9th/domain/store/converter/StoreConverter.java new file mode 100644 index 0000000..614a70a --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/converter/StoreConverter.java @@ -0,0 +1,35 @@ +package com.example.umc9th.domain.store.converter; + +import com.example.umc9th.domain.store.dto.res.StoreResDTO; +import com.example.umc9th.domain.store.entity.Store; + +public class StoreConverter { + + public static StoreResDTO.Search toSearchDTO(Store store){ + return StoreResDTO.Search.builder() + .storeId(store.getId()) + .name(store.getName()) + .managerNumber(store.getManagerNumber()) + .detailAddress(store.getDetailAddress()) + .locationId(store.getLocation().getId()) + .build(); + } + +// public static BaseResDTO.PageDTO toPageDTO(Page page){ +// List content = page.getContent().stream().map(StoreConverter::toSearchDTO).toList(); +// return BaseResDTO.PageDTO.builder() +// .content(content) +// .currentPage(page.getNumber()) +// .totalPages(page.getTotalPages()) +// .totalElements(page.getTotalElements()) +// .isFirst(page.isFirst()) +// .isLast(page.isLast()) +// .build(); +// } + + public static StoreResDTO.Add toAddDTO(Store store){ + return StoreResDTO.Add.builder() + .storeId(store.getId()) + .build(); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/dto/req/LocationReqDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/req/LocationReqDTO.java new file mode 100644 index 0000000..5875799 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/req/LocationReqDTO.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.store.dto.req; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class LocationReqDTO { + private String name; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/dto/req/StoreReqDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/req/StoreReqDTO.java new file mode 100644 index 0000000..dbbe910 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/req/StoreReqDTO.java @@ -0,0 +1,14 @@ +package com.example.umc9th.domain.store.dto.req; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class StoreReqDTO { + private String name; + private Long managerNumber; + private String detailAddress; + private Long locationId; + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/dto/res/LocationResDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/res/LocationResDTO.java new file mode 100644 index 0000000..3e1eef9 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/res/LocationResDTO.java @@ -0,0 +1,13 @@ +package com.example.umc9th.domain.store.dto.res; + +import lombok.Builder; +import lombok.Getter; + +public class LocationResDTO { + + @Getter + @Builder + public static class Add{ + private Long locationId; + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/dto/res/StoreResDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/res/StoreResDTO.java new file mode 100644 index 0000000..3a644ae --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/dto/res/StoreResDTO.java @@ -0,0 +1,26 @@ +package com.example.umc9th.domain.store.dto.res; + +import lombok.Builder; +import lombok.Getter; + +public class StoreResDTO{ + + @Getter + @Builder + public static class Search{ + private Long storeId; + private String name; + private Long managerNumber; + private String detailAddress; + private Long locationId; + } + + @Getter + @Builder + public static class Add{ + private Long storeId; + } + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/entity/Location.java b/week10/code/src/main/java/com/example/umc9th/domain/store/entity/Location.java new file mode 100644 index 0000000..bf2d2e8 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/entity/Location.java @@ -0,0 +1,26 @@ +package com.example.umc9th.domain.store.entity; + +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.HashSet; +import java.util.Set; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "location") +public class Location extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", nullable = false) + private String name; + + @OneToMany(mappedBy = "location") + private Set storeList = new HashSet<>(); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/entity/Store.java b/week10/code/src/main/java/com/example/umc9th/domain/store/entity/Store.java new file mode 100644 index 0000000..043f46b --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/entity/Store.java @@ -0,0 +1,81 @@ +package com.example.umc9th.domain.store.entity; + +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.BatchSize; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "store") +public class Store extends BaseEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "manager_number", nullable = false) + private Long managerNumber; + + @Column(name = "detail_address", nullable = false) + private String detailAddress; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "location_id") + private Location location; + + @OneToMany(mappedBy = "store", cascade = CascadeType.REMOVE, orphanRemoval = true) + @BatchSize(size=10) + private Set missionList = new HashSet<>(); + + @OneToMany(mappedBy = "store") + private Set reviewList = new HashSet<>(); + + @Column(nullable = false) + private String sortKey; + + @PrePersist @PreUpdate + private void syncSortKey() { + this.sortKey = buildSortKey(this.name); + } + public static String buildSortKey(String name) { + if (name == null) return ""; + name = name.trim(); + + StringBuilder sb = new StringBuilder(name.length() * 2); + name.codePoints().forEach(cp -> { + int bucket = + (cp >= 0xAC00 && cp <= 0xD7A3) ? 1 : // 가~힣 (완성형) + (cp >= 'A' && cp <= 'Z') ? 2 : + (cp >= 'a' && cp <= 'z') ? 3 : 4; + sb.append((char) ('0' + bucket)); + // 소문자화(유니코드 안전) + sb.append(new String(Character.toChars(Character.toLowerCase(cp)))); + }); + return sb.toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Store)) return false; + Store store = (Store) o; + return Objects.equals(getLocation(), store.getLocation()); + } + @Override + public int hashCode() { + return Objects.hash(getLocation()); + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/exception/LocationException.java b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/LocationException.java new file mode 100644 index 0000000..acf69a0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/LocationException.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.store.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; + +public class LocationException extends GeneralException { + public LocationException(BaseErrorCode code) { + super(code); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/exception/StoreException.java b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/StoreException.java new file mode 100644 index 0000000..a6e94bc --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/StoreException.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.store.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; + +public class StoreException extends GeneralException { + public StoreException(BaseErrorCode code) { + super(code); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/exception/code/LocationErrorCode.java b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/code/LocationErrorCode.java new file mode 100644 index 0000000..5f307aa --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/code/LocationErrorCode.java @@ -0,0 +1,18 @@ +package com.example.umc9th.domain.store.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum LocationErrorCode implements BaseErrorCode { + + LOCATION_NOT_FOUND(HttpStatus.BAD_REQUEST, "LOCATION400_1", "존재하지 않는 지역입니다.") + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/exception/code/StoreErrorCode.java b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/code/StoreErrorCode.java new file mode 100644 index 0000000..6671d1d --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/exception/code/StoreErrorCode.java @@ -0,0 +1,26 @@ +package com.example.umc9th.domain.store.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum StoreErrorCode implements BaseErrorCode { + + REGION_NOT_EXIST(HttpStatus.BAD_REQUEST, "STORE400_1", "잘못된 요청입니다. 지역을 지정해주세요."), + KEYWORD_NOT_EXIST(HttpStatus.BAD_REQUEST, "STORE400_2", "잘못된 요청입니다. 검색어를 입력해주세요."), + SORT_NOT_FOUND(HttpStatus.BAD_REQUEST, "STORE400_3", "잘못된 요청입니다. 해당하는 정렬이 없습니다."), + STORE_NOT_FOUND(HttpStatus.BAD_REQUEST, "STORE400_4", "해당하는 가게를 찾지 못했습니다."), + + + ; + + + + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/repository/LocationRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/LocationRepository.java new file mode 100644 index 0000000..8b319c1 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/LocationRepository.java @@ -0,0 +1,7 @@ +package com.example.umc9th.domain.store.repository; + +import com.example.umc9th.domain.store.entity.Location; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface LocationRepository extends JpaRepository { +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreQueryDSL.java b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreQueryDSL.java new file mode 100644 index 0000000..f0c5704 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreQueryDSL.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.store.repository; + +import com.example.umc9th.domain.store.entity.Store; +import com.querydsl.core.types.Predicate; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface StoreQueryDSL { + Page searchStores(Predicate predicate, String sort, Pageable pageable); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreQueryDSLImpl.java b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreQueryDSLImpl.java new file mode 100644 index 0000000..19ece47 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreQueryDSLImpl.java @@ -0,0 +1,69 @@ +package com.example.umc9th.domain.store.repository; + +import com.example.umc9th.domain.store.entity.QLocation; +import com.example.umc9th.domain.store.entity.QStore; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.exception.StoreException; +import com.example.umc9th.domain.store.exception.code.StoreErrorCode; +import com.querydsl.core.types.OrderSpecifier; +import com.querydsl.core.types.Predicate; +import com.querydsl.jpa.impl.JPAQuery; +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.support.PageableExecutionUtils; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +@RequiredArgsConstructor +public class StoreQueryDSLImpl implements StoreQueryDSL { + + private final EntityManager em; + + @Override + public Page searchStores(Predicate predicate, String sort, Pageable pageable) { + JPAQueryFactory queryFactory = new JPAQueryFactory(em); + + QStore store = QStore.store; + QLocation location = QLocation.location; + + //3. 정렬 - 최신순, 이름순 + OrderSpecifier[] order; + if("latest".equals(sort)){ + order = new OrderSpecifier[] {store.createdAt.desc()}; + } + else if("name".equals(sort)){ + order = new OrderSpecifier[] { + store.sortKey.asc(), + store.createdAt.desc() + }; + } + else{ + throw new StoreException(StoreErrorCode.SORT_NOT_FOUND); //Exception 추가 + } + + // 4-1. 데이터 목록 조회 (OFFSET 페이징) + List results = queryFactory + .selectFrom(store) + .join(store.location, location).fetchJoin() //StoreResDTO의 locationId 응답 위해 fetchJoin + .where(predicate) + .orderBy(order) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .fetch(); + + // 4-2. 전체 개수 조회 (카운트 쿼리) + JPAQuery total = queryFactory + .select(store.count()) + .from(store) + .where(predicate); + + return PageableExecutionUtils.getPage(results, pageable, total::fetchOne); + +// return new PageImpl<>(results, pageable, (total != null) ? total : 0L); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreRepository.java b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreRepository.java new file mode 100644 index 0000000..75aa658 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/repository/StoreRepository.java @@ -0,0 +1,12 @@ +package com.example.umc9th.domain.store.repository; + +import com.example.umc9th.domain.store.entity.Store; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface StoreRepository extends JpaRepository, StoreQueryDSL { + + Optional findByName(String name); + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/service/LocationService.java b/week10/code/src/main/java/com/example/umc9th/domain/store/service/LocationService.java new file mode 100644 index 0000000..538127a --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/service/LocationService.java @@ -0,0 +1,25 @@ +package com.example.umc9th.domain.store.service; + +import com.example.umc9th.domain.store.dto.req.LocationReqDTO; +import com.example.umc9th.domain.store.entity.Location; +import com.example.umc9th.domain.store.repository.LocationRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class LocationService { + private final LocationRepository locationRepository; + + @Transactional + public Location addLocation(LocationReqDTO request){ + + Location location = Location.builder() + .name(request.getName()) + .build(); + + return locationRepository.save(location); + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/store/service/StoreService.java b/week10/code/src/main/java/com/example/umc9th/domain/store/service/StoreService.java new file mode 100644 index 0000000..6e349f0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/store/service/StoreService.java @@ -0,0 +1,73 @@ +package com.example.umc9th.domain.store.service; + +import com.example.umc9th.domain.store.dto.req.StoreReqDTO; +import com.example.umc9th.domain.store.entity.Location; +import com.example.umc9th.domain.store.entity.QStore; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.exception.LocationException; +import com.example.umc9th.domain.store.exception.StoreException; +import com.example.umc9th.domain.store.exception.code.LocationErrorCode; +import com.example.umc9th.domain.store.exception.code.StoreErrorCode; +import com.example.umc9th.domain.store.repository.LocationRepository; +import com.example.umc9th.domain.store.repository.StoreRepository; +import com.querydsl.core.BooleanBuilder; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class StoreService { + private final StoreRepository storeRepository; + private final LocationRepository locationRepository; + + public Page searchStores(List region, String keyword, String sort, Pageable pageable) { + QStore store = QStore.store; + + BooleanBuilder mainBuilder = new BooleanBuilder(); + + //1. 필터링 - 지역 기반 + if (region != null && !region.isEmpty()) { + BooleanBuilder regionBuilder = new BooleanBuilder(); + for(String rg : region){ + regionBuilder.or(store.detailAddress.contains(rg)); + } + mainBuilder.and(regionBuilder); + } + else{ + throw new StoreException(StoreErrorCode.REGION_NOT_EXIST); //Exception 추가 + } + + //2. 검색 - 공백 기준 + if(StringUtils.hasText(keyword)){ + BooleanBuilder keywordBuilder = new BooleanBuilder(); + String[] words = keyword.split("\\s+"); + for(String word : words){ + keywordBuilder.or(store.name.contains(word)); + } + mainBuilder.and(keywordBuilder); + } + else{ + throw new StoreException(StoreErrorCode.KEYWORD_NOT_EXIST); //Exception 추가 + } + + return storeRepository.searchStores(mainBuilder, sort, pageable); + } + + @Transactional + public Store addStore(StoreReqDTO request){ + Location location = locationRepository.findById(request.getLocationId()).orElseThrow(() -> new LocationException(LocationErrorCode.LOCATION_NOT_FOUND)); + Store store = Store.builder() + .name(request.getName()) + .detailAddress(request.getDetailAddress()) + .managerNumber(request.getManagerNumber()) + .location(location) + .build(); + return storeRepository.save(store); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/controller/TestController.java b/week10/code/src/main/java/com/example/umc9th/domain/test/controller/TestController.java new file mode 100644 index 0000000..9def1e9 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/controller/TestController.java @@ -0,0 +1,45 @@ +package com.example.umc9th.domain.test.controller; + +import com.example.umc9th.domain.test.converter.TestConverter; +import com.example.umc9th.domain.test.dto.res.TestResDTO; +import com.example.umc9th.domain.test.service.query.TestQueryService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/temp") +public class TestController { + + private final TestQueryService testQueryService; + + @GetMapping("/test") + public ApiResponse test() throws Exception{ + //응답 코드 정의 + GeneralSuccessCode code = GeneralSuccessCode.OK; + return ApiResponse.onSuccess(code, TestConverter.toTestingDTO("This is Test!")); + } + + @GetMapping("/exception") + public ApiResponse exception(@RequestParam Long flag){ + + testQueryService.checkFlag(flag); + + GeneralSuccessCode code = GeneralSuccessCode.OK; + return ApiResponse.onSuccess(code, TestConverter.toExceptionDTO("This is Test!")); + } + + @GetMapping("/webhook") + public ApiResponse webhookTest(){ + try{ + throw new Exception(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/converter/TestConverter.java b/week10/code/src/main/java/com/example/umc9th/domain/test/converter/TestConverter.java new file mode 100644 index 0000000..d0cac28 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/converter/TestConverter.java @@ -0,0 +1,18 @@ +package com.example.umc9th.domain.test.converter; + +import com.example.umc9th.domain.test.dto.res.TestResDTO; + +public class TestConverter { + + public static TestResDTO.Testing toTestingDTO(String testing){ + return TestResDTO.Testing.builder() + .testing(testing) + .build(); + } + + public static TestResDTO.Exception toExceptionDTO(String testing){ + return TestResDTO.Exception.builder() + .testString(testing) + .build(); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/dto/req/TestReqDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/test/dto/req/TestReqDTO.java new file mode 100644 index 0000000..294a23a --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/dto/req/TestReqDTO.java @@ -0,0 +1,6 @@ +package com.example.umc9th.domain.test.dto.req; + +public class TestReqDTO { + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/dto/res/TestResDTO.java b/week10/code/src/main/java/com/example/umc9th/domain/test/dto/res/TestResDTO.java new file mode 100644 index 0000000..505fedf --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/dto/res/TestResDTO.java @@ -0,0 +1,18 @@ +package com.example.umc9th.domain.test.dto.res; + +import lombok.Builder; +import lombok.Getter; + +public class TestResDTO { + @Builder + @Getter + public static class Testing{ + private String testing; + } + + @Builder + @Getter + public static class Exception{ + private String testString; + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/exception/TestException.java b/week10/code/src/main/java/com/example/umc9th/domain/test/exception/TestException.java new file mode 100644 index 0000000..1faf200 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/exception/TestException.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.test.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; + +public class TestException extends GeneralException { + public TestException(BaseErrorCode code) { + super(code); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/exception/code/TestErrorCode.java b/week10/code/src/main/java/com/example/umc9th/domain/test/exception/code/TestErrorCode.java new file mode 100644 index 0000000..4b25f0c --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/exception/code/TestErrorCode.java @@ -0,0 +1,18 @@ +package com.example.umc9th.domain.test.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum TestErrorCode implements BaseErrorCode { + + TEST_EXCEPTION(HttpStatus.BAD_REQUEST, "TEST400_1", "이거는 테스트"); + + private final HttpStatus status; + private final String code; + private final String message; + +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandService.java b/week10/code/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandService.java new file mode 100644 index 0000000..b1102dd --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandService.java @@ -0,0 +1,4 @@ +package com.example.umc9th.domain.test.service.command; + +public interface TestCommandService { +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandServiceImpl.java b/week10/code/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandServiceImpl.java new file mode 100644 index 0000000..3e5a276 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandServiceImpl.java @@ -0,0 +1,4 @@ +package com.example.umc9th.domain.test.service.command; + +public class TestCommandServiceImpl { +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryService.java b/week10/code/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryService.java new file mode 100644 index 0000000..4b8f749 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryService.java @@ -0,0 +1,6 @@ +package com.example.umc9th.domain.test.service.query; + +public interface TestQueryService { + void checkFlag(Long flag); +// void webhookTest(); +} diff --git a/week10/code/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryServiceImpl.java b/week10/code/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryServiceImpl.java new file mode 100644 index 0000000..3e12cf2 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryServiceImpl.java @@ -0,0 +1,18 @@ +package com.example.umc9th.domain.test.service.query; + +import com.example.umc9th.domain.test.exception.TestException; +import com.example.umc9th.domain.test.exception.code.TestErrorCode; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class TestQueryServiceImpl implements TestQueryService { + + @Override + public void checkFlag(Long flag){ + if(flag == 1){ + throw new TestException(TestErrorCode.TEST_EXCEPTION); + } + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/annotation/ExistFoods.java b/week10/code/src/main/java/com/example/umc9th/global/annotation/ExistFoods.java new file mode 100644 index 0000000..b5c8041 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/annotation/ExistFoods.java @@ -0,0 +1,18 @@ +package com.example.umc9th.global.annotation; + +import com.example.umc9th.global.validator.FoodExistValidator; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.*; + +@Documented +@Constraint(validatedBy = FoodExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistFoods { + //여기서 디폴트 메시지를 설정합니다. + String message() default "해당 음식이 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/annotation/ValidPage.java b/week10/code/src/main/java/com/example/umc9th/global/annotation/ValidPage.java new file mode 100644 index 0000000..38e9439 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/annotation/ValidPage.java @@ -0,0 +1,19 @@ +package com.example.umc9th.global.annotation; + + +import com.example.umc9th.global.validator.FoodExistValidator; +import com.example.umc9th.global.validator.PageValidator; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.*; + +@Documented +@Constraint(validatedBy = PageValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ValidPage { + String message() default "page는 1 이상이어야 합니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java new file mode 100644 index 0000000..79bba77 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java @@ -0,0 +1,37 @@ +package com.example.umc9th.global.apiPayload; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.code.BaseSuccessCode; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +@JsonPropertyOrder({"isSuccess", "code", "message", "result"}) +public class ApiResponse { + + @JsonProperty("isSuccess") + private final Boolean isSuccess; + + @JsonProperty("code") + private final String code; + + @JsonProperty("message") + private final String message; + + @JsonProperty("result") + private final T result; + + // 성공한 경우 (result 포함) + public static ApiResponse onSuccess(BaseSuccessCode code, T result){ + return new ApiResponse<>(true, code.getCode(), code.getMessage(), result); + } + + // 실패한 경우 (result 포함) + public static ApiResponse onFailure(BaseErrorCode code, T result) { + return new ApiResponse<>(false, code.getCode(), code.getMessage(), result); + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/BaseErrorCode.java b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/BaseErrorCode.java new file mode 100644 index 0000000..d1e67b6 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/BaseErrorCode.java @@ -0,0 +1,9 @@ +package com.example.umc9th.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseErrorCode { + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/BaseSuccessCode.java b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/BaseSuccessCode.java new file mode 100644 index 0000000..19d1b22 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/BaseSuccessCode.java @@ -0,0 +1,9 @@ +package com.example.umc9th.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseSuccessCode { + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralErrorCode.java b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralErrorCode.java new file mode 100644 index 0000000..4dddcf0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralErrorCode.java @@ -0,0 +1,28 @@ +package com.example.umc9th.global.apiPayload.code; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum GeneralErrorCode implements BaseErrorCode { + + + BAD_REQUEST(HttpStatus.BAD_REQUEST,"COMMON400_1","잘못된 요청입니다."), + UNAUTHORIZED(HttpStatus.UNAUTHORIZED,"AUTH401_1","인증이 필요합니다."), + FORBIDDEN(HttpStatus.FORBIDDEN,"AUTH403_1","요청이 거부되었습니다."), + NOT_FOUND(HttpStatus.NOT_FOUND,"COMMON404_1","요청한 리소스를 찾을 수 없습니다."), + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR,"COMMON500_1","예기치 않은 서버 에러가 발생했습니다."), + VALID_FAIL(HttpStatus.BAD_REQUEST, "COMMON405_1", "유효하지 않은 요청"), + + PAGE_INVALID(HttpStatus.BAD_REQUEST, "PAGE400_1", "유효하지 않은 페이지 범위입니다.") + ; + + private final HttpStatus status; + private final String code; + private final String message; + + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralSuccessCode.java b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralSuccessCode.java new file mode 100644 index 0000000..ca5c305 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralSuccessCode.java @@ -0,0 +1,16 @@ +package com.example.umc9th.global.apiPayload.code; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum GeneralSuccessCode implements BaseSuccessCode { + + OK(HttpStatus.OK, "COMMON200_1", "요청이 정상적으로 처리되었습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/apiPayload/exception/GeneralException.java b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/exception/GeneralException.java new file mode 100644 index 0000000..64d2a1b --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/exception/GeneralException.java @@ -0,0 +1,11 @@ +package com.example.umc9th.global.apiPayload.exception; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class GeneralException extends RuntimeException{ + private final BaseErrorCode code; +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java new file mode 100644 index 0000000..5ce92ff --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java @@ -0,0 +1,69 @@ +package com.example.umc9th.global.apiPayload.handler; + +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.code.GeneralErrorCode; +import com.example.umc9th.global.apiPayload.exception.GeneralException; +import com.example.umc9th.global.service.DiscordWebhookService; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.HashMap; +import java.util.Map; + +@RestControllerAdvice +@RequiredArgsConstructor +@Slf4j +public class GeneralExceptionAdvice { + + private final DiscordWebhookService discordWebhookService; + + // 애플리케이션에서 발생하는 커스텀 예외를 처리 + @ExceptionHandler(GeneralException.class) + public ResponseEntity> handleException(GeneralException ex){ + return ResponseEntity.status(ex.getCode().getStatus()) + .body(ApiResponse.onFailure(ex.getCode(), null)); + } + + // 컨트롤러 메서드에서 @Valid 어노테이션을 사용하여 DTO의 유효성 검사를 수행 + @ExceptionHandler(MethodArgumentNotValidException.class) + protected ResponseEntity>> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { + // 검사에 실패한 필드와 그에 대한 메시지를 저장하는 Map + Map errors = new HashMap<>(); + ex.getBindingResult().getFieldErrors().forEach(error -> + errors.put(error.getField(), error.getDefaultMessage()) + ); + + GeneralErrorCode code = GeneralErrorCode.VALID_FAIL; + ApiResponse> errorResponse = ApiResponse.onFailure(code, errors); + + // 에러 코드, 메시지와 함께 errors를 반환 + return ResponseEntity.status(code.getStatus()).body(errorResponse); + } + + // 그 외의 정의되지 않은 모든 예외 처리 + @ExceptionHandler(Exception.class) + public ResponseEntity> handleException(Exception ex, HttpServletRequest request){ + + // 오류난 url과 httpMethod 가져오기 + String url = request.getRequestURI(); + String method = request.getMethod(); + + // 로그 출력 + log.error("[500 ERROR] {} {} - {}", method, url, ex.getMessage(), ex); + + // 웹훅으로 전송 + discordWebhookService.sendErrorToWebhook(ex, url, method); + + + BaseErrorCode code = GeneralErrorCode.INTERNAL_SERVER_ERROR; + return ResponseEntity.status(code.getStatus()) + .body(ApiResponse.onFailure(code, null)); + } + +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/controller/AuthController.java b/week10/code/src/main/java/com/example/umc9th/global/auth/controller/AuthController.java new file mode 100644 index 0000000..d3fc663 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/controller/AuthController.java @@ -0,0 +1,60 @@ +package com.example.umc9th.global.auth.controller; + +import com.example.umc9th.domain.member.dto.res.MemberResDTO; +import com.example.umc9th.domain.member.exception.code.MemberSuccessCode; +import com.example.umc9th.domain.member.service.MemberService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.auth.dto.KakaoResDTO; +import com.example.umc9th.global.auth.service.KakaoService; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseCookie; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +import java.time.Duration; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/auth") +public class AuthController { + private final KakaoService kakaoService; + private final MemberService memberService; + + + @Operation( + summary = "카카오 소셜 로그인 API", + description = "카카오 로그인 URL: https://kauth.kakao.com/oauth/authorize?client_id=fc96b5b695d36b6cd576b67c9fdf0085&redirect_uri=http://localhost:8080/api/auth/kakao/callback&response_type=code" + ) + @GetMapping("/kakao/callback") + public ApiResponse kakaoLogin(@RequestParam("code") String code, HttpServletResponse response){ + // 1. 인가 코드로 카카오 액세스 토큰 발급 + String accessToken = kakaoService.getAccessToken(code); + + // 2. 카카오 액세스 토큰으로 사용자 정보 조회 + KakaoResDTO.UserInfoDTO kakaoUserInfo = kakaoService.getUserInfo(accessToken); + + // 3. 회원가입 및 로그인 + MemberResDTO.LoginTokenDTO result = memberService.loginOrSignup(kakaoUserInfo); + + // AccessToken을 Header에 설정 + response.setHeader("Authorization", "Bearer " + result.accessToken()); + + // RefreshToken을 HttpOnly 쿠키로 설정 + ResponseCookie cookie = ResponseCookie.from("refreshToken", result.refreshToken()) + .httpOnly(true) + .secure(false) // HTTPS만 허용할 경우 true + .path("/") + .maxAge(Duration.ofDays(7)) + .build(); + response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString()); + + // 3. 우리 서비스 로그인/회원가입 후 AccessToken 발급 + return ApiResponse.onSuccess(MemberSuccessCode.FOUND, MemberResDTO.LoginDTO.of(result.member())); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/details/CustomUserDetails.java b/week10/code/src/main/java/com/example/umc9th/global/auth/details/CustomUserDetails.java new file mode 100644 index 0000000..bb720d0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/details/CustomUserDetails.java @@ -0,0 +1,31 @@ +package com.example.umc9th.global.auth.details; + +import com.example.umc9th.domain.member.entity.Member; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.List; + +@RequiredArgsConstructor +public class CustomUserDetails implements UserDetails { + + private final Member member; + + @Override + public Collection getAuthorities() { + return List.of(() -> member.getRole().toString()); + } + + @Override + public String getPassword() { + return member.getPassword(); + } + + @Override + public String getUsername() { + return member.getEmail(); + } +} + diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/details/CustomUserDetailsService.java b/week10/code/src/main/java/com/example/umc9th/global/auth/details/CustomUserDetailsService.java new file mode 100644 index 0000000..a68bc64 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/details/CustomUserDetailsService.java @@ -0,0 +1,28 @@ +package com.example.umc9th.global.auth.details; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.exception.code.MemberErrorCode; +import com.example.umc9th.domain.member.repository.MemberRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class CustomUserDetailsService implements UserDetailsService { + + private final MemberRepository memberRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + // 검증할 Member 조회 + Member member = memberRepository.findByEmail(username) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + // CustomUserDetails 반환 + return new CustomUserDetails(member); + } +} + diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/dto/KakaoResDTO.java b/week10/code/src/main/java/com/example/umc9th/global/auth/dto/KakaoResDTO.java new file mode 100644 index 0000000..6df8509 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/dto/KakaoResDTO.java @@ -0,0 +1,49 @@ +package com.example.umc9th.global.auth.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class KakaoResDTO { + + // 액세스 토큰 응답 DTO + public record TokenDTO( + @JsonProperty("access_token") + String accessToken, + + @JsonProperty("refresh_token") + String refreshToken, + + @JsonProperty("expires_in") + Integer expiresIn, + + @JsonProperty("refresh_token_expires_in") + Integer refreshTokenExpiresIn, + + @JsonProperty("token_type") + String tokenType, + + @JsonProperty("scope") + String scope + ) {} + + // 사용자 정보 응답 DTO + public record UserInfoDTO( + Long id, // 카카오 회원 번호 + + @JsonProperty("connected_at") + String connectedAt, + + @JsonProperty("kakao_account") + KakaoAccount kakaoAccount + ) { + + public record KakaoAccount( + @JsonProperty("email_needs_agreement") + Boolean emailNeedsAgreement, + + @JsonProperty("has_email") + Boolean hasEmail, + + String email + ) {} + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/enums/Role.java b/week10/code/src/main/java/com/example/umc9th/global/auth/enums/Role.java new file mode 100644 index 0000000..673e30c --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/enums/Role.java @@ -0,0 +1,5 @@ +package com.example.umc9th.global.auth.enums; + +public enum Role { + ROLE_ADMIN, ROLE_USER +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/service/KakaoService.java b/week10/code/src/main/java/com/example/umc9th/global/auth/service/KakaoService.java new file mode 100644 index 0000000..52621f4 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/service/KakaoService.java @@ -0,0 +1,94 @@ +package com.example.umc9th.global.auth.service; + +import com.example.umc9th.global.auth.dto.KakaoResDTO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.userdetails.User; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +@Slf4j +@Service +@RequiredArgsConstructor +public class KakaoService { + + @Value("${kakao.client-id}") + private String clientId; + + @Value("${kakao.redirect-uri}") + private String redirectUri; + + @Value("${kakao.token-uri}") + private String tokenUri; + + @Value("${kakao.user-info-uri}") + private String userInfoUri; + + private final RestTemplate restTemplate = new RestTemplate(); + + // 1. 인가 코드로 액세스 토큰 요청 (Step 2) + public String getAccessToken(String code) { + // HTTP Header 생성 + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); + + // HTTP Body 생성 + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("grant_type", "authorization_code"); + body.add("client_id", clientId); + body.add("redirect_uri", redirectUri); + body.add("code", code); // 프론트에서 받은 인가 코드 + + // HTTP 요청 보내기 + HttpEntity> kakaoTokenRequest = new HttpEntity<>(body, headers); + + try { + ResponseEntity response = restTemplate.exchange( + tokenUri, + HttpMethod.POST, + kakaoTokenRequest, + KakaoResDTO.TokenDTO.class + ); + + return response.getBody().accessToken(); + } catch (Exception e) { + log.error("카카오 토큰 발급 실패", e); + throw new RuntimeException("카카오 액세스 토큰을 가져오는데 실패했습니다."); + } + } + + // 2. 액세스 토큰으로 사용자 정보 조회 (Step 3) + public KakaoResDTO.UserInfoDTO getUserInfo(String accessToken) { + // HTTP Header 생성 + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Bearer " + accessToken); + headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); + + // HTTP 요청 보내기 + HttpEntity> kakaoUserInfoRequest = new HttpEntity<>(headers); + + try { + ResponseEntity response = restTemplate.exchange( + userInfoUri, + HttpMethod.GET, // or POST + kakaoUserInfoRequest, + KakaoResDTO.UserInfoDTO.class + ); + + return response.getBody(); + } catch (Exception e) { + log.error("카카오 사용자 정보 조회 실패", e); + throw new RuntimeException("카카오 사용자 정보를 가져오는데 실패했습니다."); + } + } + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/token/AuthenticationEntryPointImpl.java b/week10/code/src/main/java/com/example/umc9th/global/auth/token/AuthenticationEntryPointImpl.java new file mode 100644 index 0000000..21b81f0 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/token/AuthenticationEntryPointImpl.java @@ -0,0 +1,33 @@ +package com.example.umc9th.global.auth.token; + +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralErrorCode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import java.io.IOException; + +public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint { + private final ObjectMapper objectMapper = new ObjectMapper(); + + + @Override + public void commence( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException authException + ) throws IOException { + response.setContentType("application/json;charset=UTF-8"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + + ApiResponse errorResponse = ApiResponse.onFailure( + GeneralErrorCode.UNAUTHORIZED, + null + ); + + objectMapper.writeValue(response.getOutputStream(), errorResponse); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/token/JwtAuthFilter.java b/week10/code/src/main/java/com/example/umc9th/global/auth/token/JwtAuthFilter.java new file mode 100644 index 0000000..d296038 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/token/JwtAuthFilter.java @@ -0,0 +1,62 @@ +package com.example.umc9th.global.auth.token; + +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralErrorCode; +import com.example.umc9th.global.auth.details.CustomUserDetailsService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + + +@RequiredArgsConstructor +public class JwtAuthFilter extends OncePerRequestFilter { + + private final JwtUtil jwtUtil; + private final CustomUserDetailsService customUserDetailsService; + + @Override + protected void doFilterInternal( + @NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain + ) throws ServletException, IOException { + + // 토큰 가져오기 + String token = request.getHeader("Authorization"); + // token이 없거나 Bearer가 아니면 넘기기 + if (token == null || !token.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + // Bearer이면 추출 + token = token.replace("Bearer ", ""); + // AccessToken 검증하기: 올바른 토큰이면 + if (jwtUtil.isValid(token)) { + // 토큰에서 이메일 추출 + String email = jwtUtil.getEmail(token); + // 인증 객체 생성: 이메일로 찾아온 뒤, 인증 객체 생성 + UserDetails user = customUserDetailsService.loadUserByUsername(email); + Authentication auth = new UsernamePasswordAuthenticationToken( + user, + null, + user.getAuthorities() + ); + // 인증 완료 후 SecurityContextHolder에 넣기 + SecurityContextHolder.getContext().setAuthentication(auth); + } + filterChain.doFilter(request, response); + + + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/auth/token/JwtUtil.java b/week10/code/src/main/java/com/example/umc9th/global/auth/token/JwtUtil.java new file mode 100644 index 0000000..8e00402 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/auth/token/JwtUtil.java @@ -0,0 +1,101 @@ +package com.example.umc9th.global.auth.token; + +import com.example.umc9th.global.auth.details.CustomUserDetails; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.stream.Collectors; + +@Component +public class JwtUtil { + + private final SecretKey secretKey; + private final Duration accessExpiration; + private final Duration refreshExpiration; + + public JwtUtil( + @Value("${jwt.token.secretKey}") String secret, + @Value("${jwt.token.expiration.access}") Long accessExpiration, + @Value("${jwt.token.expiration.refresh}") Long refreshExpiration + ) { + this.secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); + this.accessExpiration = Duration.ofMillis(accessExpiration); + this.refreshExpiration = Duration.ofMillis(refreshExpiration); + } + + // AccessToken 생성 + public String createAccessToken(CustomUserDetails user) { + return createToken(user, accessExpiration); + } + + // RefreshToken 생성 + public String createRefreshToken(CustomUserDetails user) { + return createToken(user, refreshExpiration); + } + + /** 토큰에서 이메일 가져오기 + * + * @param token 유저 정보를 추출할 토큰 + * @return 유저 이메일을 토큰에서 추출합니다 + */ + public String getEmail(String token) { + try { + return getClaims(token).getPayload().getSubject(); // Parsing해서 Subject 가져오기 + } catch (JwtException e) { + return null; + } + } + + /** 토큰 유효성 확인 + * + * @param token 유효한지 확인할 토큰 + * @return True, False 반환합니다 + */ + public boolean isValid(String token) { + try { + getClaims(token); + return true; + } catch (JwtException e) { + return false; + } + } + + // 토큰 생성 + private String createToken(CustomUserDetails user, Duration expiration) { + Instant now = Instant.now(); + + // 인가 정보 + String authorities = user.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.joining(",")); + + return Jwts.builder() + .subject(user.getUsername()) // User 이메일을 Subject로 + .claim("role", authorities) + .claim("email", user.getUsername()) + .issuedAt(Date.from(now)) // 언제 발급한지 + .expiration(Date.from(now.plus(expiration))) // 언제까지 유효한지 + .signWith(secretKey) // sign할 Key + .compact(); + } + + // 토큰 정보 가져오기 + private Jws getClaims(String token) throws JwtException { + return Jwts.parser() + .verifyWith(secretKey) + .clockSkewSeconds(60) + .build() + .parseSignedClaims(token); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/config/SecurityConfig.java b/week10/code/src/main/java/com/example/umc9th/global/config/SecurityConfig.java new file mode 100644 index 0000000..c14b965 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/config/SecurityConfig.java @@ -0,0 +1,75 @@ +package com.example.umc9th.global.config; + +import com.example.umc9th.global.auth.details.CustomUserDetailsService; +import com.example.umc9th.global.auth.token.AuthenticationEntryPointImpl; +import com.example.umc9th.global.auth.token.JwtAuthFilter; +import com.example.umc9th.global.auth.token.JwtUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@EnableWebSecurity +@Configuration +@RequiredArgsConstructor +public class SecurityConfig { + + private final JwtUtil jwtUtil; + private final CustomUserDetailsService customUserDetailsService; + + private final String[] allowUris = { + "/api/member/login", + "/api/member/sign-up", + "/api/auth/kakao/callback", + "/swagger-ui/**", + "/swagger-resources/**", + "/v3/api-docs/**", + }; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(requests -> requests + .requestMatchers(allowUris).permitAll() + .requestMatchers("/admin/**").hasRole("ADMIN") + .anyRequest().authenticated() + ) + // 폼로그인 비활성화 + .formLogin(AbstractHttpConfigurer::disable) + // JwtAuthFilter를 UsernamePasswordAuthenticationFilter 앞에 추가 + .addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class) + .csrf(AbstractHttpConfigurer::disable) + .logout(logout -> logout + .logoutUrl("/logout") + .logoutSuccessUrl("/login?logout") + .permitAll() + ) + .exceptionHandling(exception -> exception.authenticationEntryPoint(authenticationEntryPoint())) + + ; + + return http.build(); + } + + @Bean + public JwtAuthFilter jwtAuthFilter() { + return new JwtAuthFilter(jwtUtil, customUserDetailsService); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public AuthenticationEntryPoint authenticationEntryPoint() { + return new AuthenticationEntryPointImpl(); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/config/SwaggerConfig.java b/week10/code/src/main/java/com/example/umc9th/global/config/SwaggerConfig.java new file mode 100644 index 0000000..60da1a8 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/config/SwaggerConfig.java @@ -0,0 +1,37 @@ +package com.example.umc9th.global.config; + + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { + + @Bean + public OpenAPI swagger() { + Info info = new Info().title("Project").description("Project Swagger").version("0.0.1"); + + // JWT 토큰 헤더 방식 + String securityScheme = "JWT TOKEN"; + SecurityRequirement securityRequirement = new SecurityRequirement().addList(securityScheme); + + Components components = new Components() + .addSecuritySchemes(securityScheme, new SecurityScheme() + .name(securityScheme) + .type(SecurityScheme.Type.HTTP) + .scheme("Bearer") + .bearerFormat("JWT")); + + return new OpenAPI() + .info(info) + .addServersItem(new Server().url("/")) + .addSecurityItem(securityRequirement) + .components(components); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/dto/PageDTO.java b/week10/code/src/main/java/com/example/umc9th/global/dto/PageDTO.java new file mode 100644 index 0000000..1c7e59e --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/dto/PageDTO.java @@ -0,0 +1,65 @@ +package com.example.umc9th.global.dto; + +import org.springframework.data.domain.Page; + +import java.util.List; +import java.util.function.Function; + +public record PageDTO( + List content, + int currentPage, + int size, + long totalElements, + int totalPages, + boolean isFirst, + boolean isLast +){ + + /** + * Page<T>를 PageDTO<T>로 변환합니다. + *

+ * 주로 DTO객체를 페이징하기 위해 사용합니다. + *

+ * + * @param pageData Page 객체 + * @param 데이터의 타입 + * @return 페이징 정보가 담긴 PageDTO + */ + public static PageDTO of(Page pageData) { + return new PageDTO<>( + pageData.getContent(), + pageData.getNumber() + 1, //page 1부터 시작 + pageData.getSize(), + pageData.getTotalElements(), + pageData.getTotalPages(), + pageData.isFirst(), + pageData.isLast() + ); + } + + /** + * Page<Entity>를 PageDTO<DTO>로 변환합니다.

+ * + * Page<Entity>의 내용을 Converter를 통해 DTO 타입으로 바꾼 뒤 PageDTO<DTO>을 생성합니다.

+ * + * @param pageData Page 객체 + * @param converter 리스트 내부의 각 요소를 변환할 함수 (사용 예: DomainConverter::toDto) + * @param (Entity) 원본 데이터 타입 + * @param (Result) 변환 후 반환할 데이터 타입 + * @return 변환된 데이터 리스트와 페이징 정보가 담긴 PageDTO + */ + public static PageDTO of(Page pageData, Function converter) { + //Function converter: Entity -> Converter -> Result + List content = pageData.getContent().stream().map(converter).toList(); + + return new PageDTO<>( + content, + pageData.getNumber() + 1, //page 1부터 시작 + pageData.getSize(), + pageData.getTotalElements(), + pageData.getTotalPages(), + pageData.isFirst(), + pageData.isLast() + ); + } +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/entity/BaseEntity.java b/week10/code/src/main/java/com/example/umc9th/global/entity/BaseEntity.java new file mode 100644 index 0000000..4d47bd7 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/entity/BaseEntity.java @@ -0,0 +1,25 @@ +package com.example.umc9th.global.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@Getter +public class BaseEntity { + + @CreatedDate + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(name = "updated_at") + private LocalDateTime updatedAt; +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/service/DiscordWebhookService.java b/week10/code/src/main/java/com/example/umc9th/global/service/DiscordWebhookService.java new file mode 100644 index 0000000..2885656 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/service/DiscordWebhookService.java @@ -0,0 +1,73 @@ +package com.example.umc9th.global.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +@Service +@RequiredArgsConstructor +@Slf4j +public class DiscordWebhookService { + //Webhook URL을 환경변수에 저장 + @Value("${alert.discord.webhook-url}") + private String webhookUrl; + + //local환경이면 enabled:false, dev환경이면 enabled:true + @Value("${alert.discord.enabled}") + private boolean webhookEnabled; + + //Spring Framework에서 제공하는 동기(Synchronous) 방식의 HTTP 클라이언트 + //다른 서버의 API를 호출할 때 사용 + private final RestTemplate restTemplate = new RestTemplate(); + + public void sendErrorToWebhook(Exception ex, String url, String method) { + try { + if(webhookEnabled){ + String message = buildMessage(ex, url, method); + + //HTTP Header 정의, Content-Type: application/json + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + // Discord body 형식({content: 내용}) + Map payload = Map.of("content", message); + + //header + body + HttpEntity> entity = new HttpEntity<>(payload, headers); + + //webhookUrl에 entity내용을 post로 전송 + restTemplate.postForEntity(webhookUrl, entity, String.class); + } + + } catch (Exception e) { + log.error("Failed to send webhook: {}", e.getMessage()); + } + } + + // Discord에 보낼 메시지 형식 + private String buildMessage(Exception ex, String url, String method) { + return """ + 🚨 **500 Internal Server Error 발생** + - URL: `%s` + - Method: `%s` + - 예외: `%s` + - 시각: `%s` + """.formatted( + url, + method, + ex.getMessage(), + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ); + } + + +} diff --git a/week10/code/src/main/java/com/example/umc9th/global/validator/FoodExistValidator.java b/week10/code/src/main/java/com/example/umc9th/global/validator/FoodExistValidator.java new file mode 100644 index 0000000..b82dcab --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/validator/FoodExistValidator.java @@ -0,0 +1,33 @@ +package com.example.umc9th.global.validator; + +import com.example.umc9th.domain.member.exception.code.FoodErrorCode; +import com.example.umc9th.domain.member.repository.FoodRepository; +import com.example.umc9th.global.annotation.ExistFoods; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class FoodExistValidator implements ConstraintValidator> { + + private final FoodRepository foodRepository; + + @Override + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = values.stream() + .allMatch(value -> foodRepository.existsById(value)); + + if (!isValid) { + // 이 부분에서 아까 디폴트 메시지를 초기화 시키고, 새로운 메시지로 덮어씌우게 됩니다. + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(FoodErrorCode.NOT_FOUND.getMessage()).addConstraintViolation(); + } + + return isValid; + + } +} \ No newline at end of file diff --git a/week10/code/src/main/java/com/example/umc9th/global/validator/PageValidator.java b/week10/code/src/main/java/com/example/umc9th/global/validator/PageValidator.java new file mode 100644 index 0000000..4b10066 --- /dev/null +++ b/week10/code/src/main/java/com/example/umc9th/global/validator/PageValidator.java @@ -0,0 +1,30 @@ +package com.example.umc9th.global.validator; + +import com.example.umc9th.domain.member.exception.code.FoodErrorCode; +import com.example.umc9th.global.annotation.ExistFoods; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.code.GeneralErrorCode; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; + +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Component; + + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class PageValidator implements ConstraintValidator { + @Override + public boolean isValid(Pageable value, ConstraintValidatorContext context) { + boolean isValid = (value.getPageNumber() > 0); + if (!isValid) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(GeneralErrorCode.PAGE_INVALID.getMessage()).addConstraintViolation(); + } + return isValid; + + } +} diff --git a/week10/code/src/main/resources/application-dev.yml b/week10/code/src/main/resources/application-dev.yml new file mode 100644 index 0000000..7c6809e --- /dev/null +++ b/week10/code/src/main/resources/application-dev.yml @@ -0,0 +1,3 @@ +alert: + discord: + enabled: true \ No newline at end of file diff --git a/week10/code/src/main/resources/application-local.yml b/week10/code/src/main/resources/application-local.yml new file mode 100644 index 0000000..6b0c581 --- /dev/null +++ b/week10/code/src/main/resources/application-local.yml @@ -0,0 +1,3 @@ +alert: + discord: + enabled: false \ No newline at end of file diff --git a/week10/code/src/main/resources/application.yml b/week10/code/src/main/resources/application.yml new file mode 100644 index 0000000..47b5dca --- /dev/null +++ b/week10/code/src/main/resources/application.yml @@ -0,0 +1,37 @@ +spring: + application: + name: "UMC9th" # "umc9th" + + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver # MySQL JDBC ???? ??? ?? + url: ${DB_URL} # jdbc:mysql://localhost:3306/{???????} + username: ${DB_USER} # MySQL ?? ?? + password: ${DB_PW} # MySQL ???? + + jpa: + database: mysql # ??? ?????? ?? ?? (MySQL) + database-platform: org.hibernate.dialect.MySQLDialect # Hibernate?? ??? MySQL ??(dialect) ?? + show-sql: true # ??? SQL ??? ??? ???? ?? ?? + hibernate: + ddl-auto: update # ?????? ?? ? ?????? ???? ??? ?? + properties: + hibernate: + format_sql: true # ???? SQL ??? ?? ?? ??? + +alert: + discord: + webhook-url: ${DISCORD_WEBHOOK_URL} + enabled: false + +jwt: + token: + secretKey: ZGh3YWlkc2F2ZXdhZXZ3b2EgMTM5ZXUgMDMxdWMyIHEyMiBAIDAgKTJFVio= + expiration: + access: 14400000 + refresh: 604800000 # 7일 + +kakao: + client-id: "fc96b5b695d36b6cd576b67c9fdf0085" + redirect-uri: "http://localhost:8080/api/auth/kakao/callback" + token-uri: "https://kauth.kakao.com/oauth/token" + user-info-uri: "https://kapi.kakao.com/v2/user/me" \ No newline at end of file diff --git a/week10/code/src/test/java/com/example/umc9th/Umc9thApplicationTests.java b/week10/code/src/test/java/com/example/umc9th/Umc9thApplicationTests.java new file mode 100644 index 0000000..bbdf1bd --- /dev/null +++ b/week10/code/src/test/java/com/example/umc9th/Umc9thApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.umc9th; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Umc9thApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git "a/week10/\354\206\214\354\205\234\353\241\234\352\267\270\354\235\270, RefreshToken \352\265\254\355\230\204.md" "b/week10/\354\206\214\354\205\234\353\241\234\352\267\270\354\235\270, RefreshToken \352\265\254\355\230\204.md" new file mode 100644 index 0000000..a99f99c --- /dev/null +++ "b/week10/\354\206\214\354\205\234\353\241\234\352\267\270\354\235\270, RefreshToken \352\265\254\355\230\204.md" @@ -0,0 +1,268 @@ +# 소셜로그인, RefreshToken 구현 + +# 카카오 소셜로그인 구현 + +--- + +# 순서 + +1. Kakao Developer 앱 생성 +2. Redirect URI 설정, REST API 키 확인 +3. [https://kauth.kakao.com/oauth/authorize?client_id={REST_API_KEY}&redirect_uri={REDIRECT_URI}&response_type=code](https://kauth.kakao.com/oauth/authorize?client_id=%7BREST_API_KEY%7D&redirect_uri=%7BREDIRECT_URI%7D&response_type=code) + + 해당 URL로 code 데이터를 받아온다. + +4. 받아온 code로 카카오 서버의 AccessToken과 RefreshToken을 받아와야 된다. + + ``` + 요청 URL: + https://kauth.kakao.com/oauth/token + + Method: + POST + + Header: + Content-type: application/x-www-form-urlencoded;charset=utf-8 + + Body (Parameter): + grant_type: authorization_code (고정) + client_id: 앱 REST API 키 + redirect_uri: 설정한 Redirect URI + code: 프론트에서 받은 인가 코드 + ``` + + [https://kauth.kakao.com/oauth/token](https://kauth.kakao.com/oauth/token) 이 URL로 필요 정보들을 담아서 POST 요청을 보내면 카카오에서 AccessToken과 RefreshToken을 발급해준다. + +5. 발급받은 AccessToken으로 사용자 정보를 가져온다. + + ``` + 요청 URL: + https://kapi.kakao.com/v2/user/me + + Method: + GET 또는 POST + + Header: + Authorization: Bearer {ACCESS_TOKEN} + Content-type: application/x-www-form-urlencoded;charset=utf-8 + ``` + + [https://kapi.kakao.com/v2/user/me](https://kapi.kakao.com/v2/user/me) 이 URL로 카카오에서 발급받은 AccessToken을 담아 GET/POST 요청을 보내면 사용자의 정보를 받아올 수 있다. (kakaoId(식별자), email 등) + + - 가져올 수 있는 정보 DTO + + ```java + @Getter + @NoArgsConstructor //역직렬화를 위한 기본 생성자 + @JsonIgnoreProperties(ignoreUnknown = true) + public class KakaoUserInfoResponseDto { + + //회원 번호 + @JsonProperty("id") + public Long id; + + //자동 연결 설정을 비활성화한 경우만 존재. + //true : 연결 상태, false : 연결 대기 상태 + @JsonProperty("has_signed_up") + public Boolean hasSignedUp; + + //서비스에 연결 완료된 시각. UTC + @JsonProperty("connected_at") + public Date connectedAt; + + //카카오싱크 간편가입을 통해 로그인한 시각. UTC + @JsonProperty("synched_at") + public Date synchedAt; + + //사용자 프로퍼티 + @JsonProperty("properties") + public HashMap properties; + + //카카오 계정 정보 + @JsonProperty("kakao_account") + public KakaoAccount kakaoAccount; + + //uuid 등 추가 정보 + @JsonProperty("for_partner") + public Partner partner; + + @Getter + @NoArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public class KakaoAccount { + + //프로필 정보 제공 동의 여부 + @JsonProperty("profile_needs_agreement") + public Boolean isProfileAgree; + + //닉네임 제공 동의 여부 + @JsonProperty("profile_nickname_needs_agreement") + public Boolean isNickNameAgree; + + //프로필 사진 제공 동의 여부 + @JsonProperty("profile_image_needs_agreement") + public Boolean isProfileImageAgree; + + //사용자 프로필 정보 + @JsonProperty("profile") + public Profile profile; + + //이름 제공 동의 여부 + @JsonProperty("name_needs_agreement") + public Boolean isNameAgree; + + //카카오계정 이름 + @JsonProperty("name") + public String name; + + //이메일 제공 동의 여부 + @JsonProperty("email_needs_agreement") + public Boolean isEmailAgree; + + //이메일이 유효 여부 + // true : 유효한 이메일, false : 이메일이 다른 카카오 계정에 사용돼 만료 + @JsonProperty("is_email_valid") + public Boolean isEmailValid; + + //이메일이 인증 여부 + //true : 인증된 이메일, false : 인증되지 않은 이메일 + @JsonProperty("is_email_verified") + public Boolean isEmailVerified; + + //카카오계정 대표 이메일 + @JsonProperty("email") + public String email; + + //연령대 제공 동의 여부 + @JsonProperty("age_range_needs_agreement") + public Boolean isAgeAgree; + + //연령대 + //참고 https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api#req-user-info + @JsonProperty("age_range") + public String ageRange; + + //출생 연도 제공 동의 여부 + @JsonProperty("birthyear_needs_agreement") + public Boolean isBirthYearAgree; + + //출생 연도 (YYYY 형식) + @JsonProperty("birthyear") + public String birthYear; + + //생일 제공 동의 여부 + @JsonProperty("birthday_needs_agreement") + public Boolean isBirthDayAgree; + + //생일 (MMDD 형식) + @JsonProperty("birthday") + public String birthDay; + + //생일 타입 + // SOLAR(양력) 혹은 LUNAR(음력) + @JsonProperty("birthday_type") + public String birthDayType; + + //성별 제공 동의 여부 + @JsonProperty("gender_needs_agreement") + public Boolean isGenderAgree; + + //성별 + @JsonProperty("gender") + public String gender; + + //전화번호 제공 동의 여부 + @JsonProperty("phone_number_needs_agreement") + public Boolean isPhoneNumberAgree; + + //전화번호 + //국내 번호인 경우 +82 00-0000-0000 형식 + @JsonProperty("phone_number") + public String phoneNumber; + + //CI 동의 여부 + @JsonProperty("ci_needs_agreement") + public Boolean isCIAgree; + + //CI, 연계 정보 + @JsonProperty("ci") + public String ci; + + //CI 발급 시각, UTC + @JsonProperty("ci_authenticated_at") + public Date ciCreatedAt; + + @Getter + @NoArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public class Profile { + + //닉네임 + @JsonProperty("nickname") + public String nickName; + + //프로필 미리보기 이미지 URL + @JsonProperty("thumbnail_image_url") + public String thumbnailImageUrl; + + //프로필 사진 URL + @JsonProperty("profile_image_url") + public String profileImageUrl; + + //프로필 사진 URL 기본 프로필인지 여부 + //true : 기본 프로필, false : 사용자 등록 + @JsonProperty("is_default_image") + public String isDefaultImage; + + //닉네임이 기본 닉네임인지 여부 + //true : 기본 닉네임, false : 사용자 등록 + @JsonProperty("is_default_nickname") + public Boolean isDefaultNickName; + + } + } + + @Getter + @NoArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public class Partner { + //고유 ID + @JsonProperty("uuid") + public String uuid; + } + + } + ``` + +6. 사용자 정보를 토대로 우리 서비스의 Token을 발급한다. + - 해당 회원이 우리 서비스에 회원가입 되어있는지 확인하고, **기존 회원**이라면 **로그인**, **신규 회원**이라면 **회원가입 후 로그인** + - 로그인이 되었기에 우리 서비스의 `AccessToken`과 `RefreshToken`이 발급된다. + + +현재 코드에선 카카오 서버 API에 RestTemplate을 통해 동기 요청을 보내는데, WebClient를 사용하면 비동기 요청으로 보낼 수 있다. + +## 참고자료 + +[[Spring] REST API 카카오 로그인 구현하기](https://ddonghyeo.tistory.com/16) + +# RefreshToken + +--- + +## 구현 목록 + +로그인 시 AccessToken, RefreshToken 발급 + +RefreshToken 재발급 API + +로그아웃 API + +## 구현 방식 + +웹 기준 로그인 시 프론트에서 + +AccessToken은 메모리(js 변수, LocalStroage 등)에 저장하고, + +RefreshToken은 쿠키에 저장한다고 가정 + +간단한 구현을 위해 RefreshToken을 DB에 저장하여 관리(화이트리스트 방식, Redis로 개선필요) \ No newline at end of file