diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.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/build.gradle b/build.gradle new file mode 100644 index 0000000..264ce8a --- /dev/null +++ b/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 = 'Demo project for Spring Boot' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +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() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/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/gradlew b/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..0ec607f --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'umc9th' diff --git a/src/main/java/com/example/umc9th/Umc9thApplication.java b/src/main/java/com/example/umc9th/Umc9thApplication.java new file mode 100644 index 0000000..bc54005 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/member/controller/MemberController.java b/src/main/java/com/example/umc9th/domain/member/controller/MemberController.java new file mode 100644 index 0000000..15d8824 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/controller/MemberController.java @@ -0,0 +1,37 @@ +package com.example.umc9th.domain.member.controller; + +import com.example.umc9th.domain.member.dto.MemberReqDTO; +import com.example.umc9th.domain.member.dto.MemberResDTO; +import com.example.umc9th.domain.member.exception.code.MemberSuccessCode; +import com.example.umc9th.domain.member.service.command.MemberCommandService; +import com.example.umc9th.domain.member.service.query.MemberQueryService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import jakarta.validation.Valid; +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 MemberController { + + private final MemberCommandService memberCommandService; + private final MemberQueryService memberQueryService; + + // 회원가입 + @PostMapping("/sign-up") + public ApiResponse signUp( + @RequestBody @Valid MemberReqDTO.JoinDTO dto + ){ + return ApiResponse.onSuccess(MemberSuccessCode.FOUND, memberCommandService.signup(dto)); + } + + // 로그인 + @PostMapping("/login") + public ApiResponse login( + @RequestBody @Valid MemberReqDTO.LoginDTO dto + ){ + return ApiResponse.onSuccess(MemberSuccessCode.FOUND, memberQueryService.login(dto)); + } +} diff --git a/src/main/java/com/example/umc9th/domain/member/converter/MemberConverter.java b/src/main/java/com/example/umc9th/domain/member/converter/MemberConverter.java new file mode 100644 index 0000000..50c04af --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/converter/MemberConverter.java @@ -0,0 +1,48 @@ +package com.example.umc9th.domain.member.converter; + +import com.example.umc9th.domain.member.dto.MemberReqDTO; +import com.example.umc9th.domain.member.dto.MemberResDTO; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.enums.Role; +import com.example.umc9th.domain.member.enums.Status; + +public class MemberConverter { + + // Entity → DTO + public static MemberResDTO.JoinDTO toJoinDTO(Member member) { + return MemberResDTO.JoinDTO.builder() + .memberId(member.getId()) + .createdAt(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) + .nickname(dto.nickname()) + .gender(dto.gender()) + .birthday(dto.birthday()) + .address(dto.address()) + .detailAddress(dto.specAddress()) + .phoneNum(dto.phoneNum()) + .point(0) + .status(Status.active) + .social_uid(null) + .social_type(null) + .build(); + } + + public static MemberResDTO.LoginDTO toLoginDTO( + Member member, + String accessToken + ) { + return MemberResDTO.LoginDTO.builder() + .memberId(member.getId()) + .accessToken(accessToken) + .build(); + } +} diff --git a/src/main/java/com/example/umc9th/domain/member/dto/MemberReqDTO.java b/src/main/java/com/example/umc9th/domain/member/dto/MemberReqDTO.java new file mode 100644 index 0000000..e201d57 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/dto/MemberReqDTO.java @@ -0,0 +1,58 @@ +package com.example.umc9th.domain.member.dto; + +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.*; + +import java.time.LocalDate; +import java.util.List; + +public class MemberReqDTO { + + public record JoinDTO( + + @NotBlank(message = "이름은 필수 입력값입니다.") + String name, + + @NotBlank(message = "이메일은 필수 입력값입니다.") + @Email(message = "올바른 이메일 형식이어야 합니다.") + String email, + + @NotBlank(message = "닉네임은 필수 입력값입니다.") + String nickname, + + @NotNull(message = "성별은 필수 입력값입니다.") + Gender gender, + + @NotNull(message = "생년월일은 필수 입력값입니다.") + @Past(message = "생년월일은 과거 날짜여야 합니다.") + LocalDate birthday, + + @NotNull(message = "주소는 필수 입력값입니다.") + Address address, + + @NotBlank(message = "전화번호는 필수 입력값입니다.") + String phoneNum, + + @NotBlank(message = "비밀번호는 필수 입력값입니다.") + String password, + + @NotBlank(message = "상세 주소는 필수 입력값입니다.") + String specAddress, + + @ExistFoods + @NotNull(message = "선호 음식 카테고리는 필수입니다.") + @Size(min = 1, message = "선호 음식은 최소 1개 이상 선택해야 합니다.") + List preferCategory + + ) {} + + // 로그인 + public record LoginDTO( + @NotBlank + String email, + @NotBlank + String password + ){} +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/member/dto/MemberResDTO.java b/src/main/java/com/example/umc9th/domain/member/dto/MemberResDTO.java new file mode 100644 index 0000000..4a3d1d4 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/dto/MemberResDTO.java @@ -0,0 +1,21 @@ +package com.example.umc9th.domain.member.dto; + +import lombok.Builder; + +import java.time.LocalDateTime; + +public class MemberResDTO { + + @Builder + public record JoinDTO( + Long memberId, + LocalDateTime createdAt + ){} + + // 로그인 + @Builder + public record LoginDTO( + Long memberId, + String accessToken + ){} +} diff --git a/src/main/java/com/example/umc9th/domain/member/entity/Food.java b/src/main/java/com/example/umc9th/domain/member/entity/Food.java new file mode 100644 index 0000000..4867baf --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/Food.java @@ -0,0 +1,23 @@ +package com.example.umc9th.domain.member.entity; + + +import com.example.umc9th.domain.member.enums.FoodName; +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "food") +public class Food { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", nullable = false, unique = true, length = 30) + @Enumerated(EnumType.STRING) + private FoodName name; +} diff --git a/src/main/java/com/example/umc9th/domain/member/entity/Member.java b/src/main/java/com/example/umc9th/domain/member/entity/Member.java new file mode 100644 index 0000000..3cbde0a --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/Member.java @@ -0,0 +1,88 @@ +package com.example.umc9th.domain.member.entity; + +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import com.example.umc9th.domain.member.enums.*; +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@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 = 20, nullable = false) + private String name; + + @Column(name = "email", length = 255, nullable = false, unique = true) + private String email; + + @Column(nullable = false) + private String password; + + @Enumerated(EnumType.STRING) + private Role role; + + @Column(name = "nickname", length = 20, nullable = false, unique = true) + private String nickname; + + @Column(name = "gender", nullable = false) + @Enumerated(EnumType.STRING) + @Builder.Default + private Gender gender = Gender.NONE; + + @Column(name = "birthday") + private LocalDate birthday; + + @Column(name = "address", nullable = false) + @Enumerated(EnumType.STRING) + private Address address; + + @Column(name = "detail_address") + private String detailAddress; + + @Column(name = "phone_num", nullable = false, length = 15) + private String phoneNum; + + @Column(name = "point", nullable = false) + @Builder.Default + private Integer point = 0; + + @Column(name = "social_uid", unique = true, length = 100) + private String social_uid; + + @Column(name = "social_type") + @Enumerated(EnumType.STRING) + private SocialType social_type = SocialType.LOCAL; + + @Column(name = "status", nullable = false) + @Enumerated(EnumType.STRING) + @Builder.Default + private Status status = Status.active; + + @Column(name = "inactive_at") + private LocalDateTime inactiveAt; + + // 회원이 참여한 미션 목록 — 회원 삭제 시 미션 매핑도 함께 삭제 + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List memberMissions = new ArrayList<>(); + + // 회원의 선호 음식 — 회원 삭제 시 연결된 유저 선호 음식 데이터도 함께 삭제 + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List memberFoods = new ArrayList<>(); +} diff --git a/src/main/java/com/example/umc9th/domain/member/entity/Term.java b/src/main/java/com/example/umc9th/domain/member/entity/Term.java new file mode 100644 index 0000000..e3ca9ba --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/Term.java @@ -0,0 +1,23 @@ +package com.example.umc9th.domain.member.entity; + + +import com.example.umc9th.domain.member.enums.TermName; +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "term") +public class Term { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", nullable = false) + @Enumerated(EnumType.STRING) + private TermName name; +} diff --git a/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberFood.java b/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberFood.java new file mode 100644 index 0000000..8a32e18 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberFood.java @@ -0,0 +1,37 @@ +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.domain.store.entity.mapping.MemberFoodStore; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table( + name = "member_food", + uniqueConstraints = @UniqueConstraint(columnNames = {"member_id", "food_id"}) +) +public class MemberFood { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id", nullable = false) + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "food_id", nullable = false) + private Food food; + + @OneToMany(mappedBy = "memberFood", cascade = CascadeType.ALL, orphanRemoval = true) + private List memberFoodStores = new ArrayList<>(); +} diff --git a/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberTerm.java b/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberTerm.java new file mode 100644 index 0000000..6c6ce9b --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberTerm.java @@ -0,0 +1,28 @@ +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 jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "member_term", + uniqueConstraints = @UniqueConstraint(columnNames = {"member_id", "term_id"})) +public class MemberTerm { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id", nullable = false) + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "term_id", nullable = false) + private Term term; +} diff --git a/src/main/java/com/example/umc9th/domain/member/enums/Address.java b/src/main/java/com/example/umc9th/domain/member/enums/Address.java new file mode 100644 index 0000000..da2453b --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/Address.java @@ -0,0 +1,12 @@ +package com.example.umc9th.domain.member.enums; + +public enum Address { + ANAM, + CHEONGDAM, + HONGDAE, + JONGRO, + ITAEWON, + SINCHON, + MYEONGDONG, + YEOKSAM +} diff --git a/src/main/java/com/example/umc9th/domain/member/enums/FoodName.java b/src/main/java/com/example/umc9th/domain/member/enums/FoodName.java new file mode 100644 index 0000000..9452055 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/FoodName.java @@ -0,0 +1,16 @@ +package com.example.umc9th.domain.member.enums; + +public enum FoodName { + KOREAN, // 한식 + JAPANESE, // 일식 + CHINESE, // 중식 + WESTERN, // 양식 + CHICKEN, // 치킨 + SNACK, // 분식 + MEAT, // 고기 + LUNCHBOX, // 도시락 + LATE_NIGHT, // 야식 + FAST_FOOD, // 패스트푸드 + DESSERT, // 디저트 + ASIAN // 아시안푸드 +} diff --git a/src/main/java/com/example/umc9th/domain/member/enums/Gender.java b/src/main/java/com/example/umc9th/domain/member/enums/Gender.java new file mode 100644 index 0000000..400401b --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/member/enums/Role.java b/src/main/java/com/example/umc9th/domain/member/enums/Role.java new file mode 100644 index 0000000..672d4db --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/Role.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.member.enums; + +public enum Role { + ROLE_ADMIN, ROLE_USER +} diff --git a/src/main/java/com/example/umc9th/domain/member/enums/SocialType.java b/src/main/java/com/example/umc9th/domain/member/enums/SocialType.java new file mode 100644 index 0000000..8d353b2 --- /dev/null +++ b/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 { + LOCAL, GOOGLE, KAKAO +} diff --git a/src/main/java/com/example/umc9th/domain/member/enums/Status.java b/src/main/java/com/example/umc9th/domain/member/enums/Status.java new file mode 100644 index 0000000..e31e7f5 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/Status.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.member.enums; + +public enum Status { + active, inactive +} diff --git a/src/main/java/com/example/umc9th/domain/member/enums/TermName.java b/src/main/java/com/example/umc9th/domain/member/enums/TermName.java new file mode 100644 index 0000000..7884ac0 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/TermName.java @@ -0,0 +1,9 @@ +package com.example.umc9th.domain.member.enums; + +public enum TermName { + SERVICE_TERMS, + PRIVACY_POLICY, + LOCATION_TERMS, + MARKETING_AGREEMENT, + AGE_CONFIRMATION +} diff --git a/src/main/java/com/example/umc9th/domain/member/exception/FoodException.java b/src/main/java/com/example/umc9th/domain/member/exception/FoodException.java new file mode 100644 index 0000000..cb2c134 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/member/exception/MemberException.java b/src/main/java/com/example/umc9th/domain/member/exception/MemberException.java new file mode 100644 index 0000000..1e4d7a1 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/member/exception/code/FoodErrorCode.java b/src/main/java/com/example/umc9th/domain/member/exception/code/FoodErrorCode.java new file mode 100644 index 0000000..d88cd68 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/exception/code/FoodErrorCode.java @@ -0,0 +1,19 @@ +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.NOT_FOUND, + "FOOD404_1", + "해당 음식을 찾지 못했습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/member/exception/code/MemberErrorCode.java b/src/main/java/com/example/umc9th/domain/member/exception/code/MemberErrorCode.java new file mode 100644 index 0000000..bc90613 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/exception/code/MemberErrorCode.java @@ -0,0 +1,27 @@ +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.NOT_FOUND, + "MEMBER404_1", + "회원을 찾을 수 없습니다." + ), + + INVALID( + HttpStatus.UNAUTHORIZED, + "MEMBER401_1", + "이메일 또는 비밀번호가 올바르지 않습니다." + ); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/member/exception/code/MemberSuccessCode.java b/src/main/java/com/example/umc9th/domain/member/exception/code/MemberSuccessCode.java new file mode 100644 index 0000000..beb41b3 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/exception/code/MemberSuccessCode.java @@ -0,0 +1,20 @@ +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/src/main/java/com/example/umc9th/domain/member/repository/FoodRepository.java b/src/main/java/com/example/umc9th/domain/member/repository/FoodRepository.java new file mode 100644 index 0000000..7bcbde6 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/repository/FoodRepository.java @@ -0,0 +1,9 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.Food; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FoodRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/umc9th/domain/member/repository/MemberFoodRepository.java b/src/main/java/com/example/umc9th/domain/member/repository/MemberFoodRepository.java new file mode 100644 index 0000000..0a6bebc --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/repository/MemberFoodRepository.java @@ -0,0 +1,7 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MemberFoodRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/umc9th/domain/member/repository/MemberRepository.java b/src/main/java/com/example/umc9th/domain/member/repository/MemberRepository.java new file mode 100644 index 0000000..e7cc1a7 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/repository/MemberRepository.java @@ -0,0 +1,14 @@ +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 { + + // 이메일로 회원 조회 (삭제되지 않은) + Optional findByEmailAndDeletedAtIsNull(String email); + + // 닉네임으로 회원 조회 (삭제되지 않은) + Optional findByNicknameAndDeletedAtIsNull(String nickname); +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/command/MemberCommandService.java b/src/main/java/com/example/umc9th/domain/member/service/command/MemberCommandService.java new file mode 100644 index 0000000..7d1822f --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/command/MemberCommandService.java @@ -0,0 +1,9 @@ +package com.example.umc9th.domain.member.service.command; + +import com.example.umc9th.domain.member.dto.MemberReqDTO; +import com.example.umc9th.domain.member.dto.MemberResDTO; + +public interface MemberCommandService { + //회원가입 + MemberResDTO.JoinDTO signup(MemberReqDTO.JoinDTO dto); +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/command/MemberCommandServiceImpl.java b/src/main/java/com/example/umc9th/domain/member/service/command/MemberCommandServiceImpl.java new file mode 100644 index 0000000..361435d --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/command/MemberCommandServiceImpl.java @@ -0,0 +1,76 @@ +package com.example.umc9th.domain.member.service.command; + +import com.example.umc9th.domain.member.converter.MemberConverter; +import com.example.umc9th.domain.member.dto.MemberReqDTO; +import com.example.umc9th.domain.member.dto.MemberResDTO; +import com.example.umc9th.domain.member.entity.Food; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import com.example.umc9th.domain.member.enums.Role; +import com.example.umc9th.domain.member.exception.FoodException; +import com.example.umc9th.domain.member.exception.code.FoodErrorCode; +import com.example.umc9th.domain.member.repository.FoodRepository; +import com.example.umc9th.domain.member.repository.MemberFoodRepository; +import com.example.umc9th.domain.member.repository.MemberRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class MemberCommandServiceImpl implements MemberCommandService { + + private final MemberRepository memberRepository; + private final MemberFoodRepository memberFoodRepository; + private final FoodRepository foodRepository; + private final PasswordEncoder passwordEncoder; + + // 회원가입 + @Override + @Transactional + public MemberResDTO.JoinDTO signup( + MemberReqDTO.JoinDTO dto + ){ + + // 솔트된 비밀번호 생성 + String salt = passwordEncoder.encode(dto.password()); + + // 사용자 생성: 유저 / 관리자는 따로 API 만들어서 관리 + Member member = MemberConverter.toMember(dto, salt, Role.ROLE_USER); + + // 회원 저장 + memberRepository.save(member); + + // 선호 음식 존재 여부 확인 + if (dto.preferCategory().size() > 1){ + List memberFoodList = new ArrayList<>(); + + // 선호 음식 ID별 조회 + for (Long id : dto.preferCategory()){ + + // 음식 존재 여부 검증 + Food food = foodRepository.findById(id) + .orElseThrow(() -> new FoodException(FoodErrorCode.NOT_FOUND)); + + // MemberFood 엔티티 생성 (컨버터 사용해야 함) + MemberFood memberFood = MemberFood.builder() + .member(member) + .food(food) + .build(); + + // 사용자 - 음식 (선호 음식) 추가 + memberFoodList.add(memberFood); + } + + // 모든 선호 음식 추가: DB 적용 + memberFoodRepository.saveAll(memberFoodList); + } + + // 응답 DTO 생성 + return MemberConverter.toJoinDTO(member); + } +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/query/MemberQueryService.java b/src/main/java/com/example/umc9th/domain/member/service/query/MemberQueryService.java new file mode 100644 index 0000000..36e06ad --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/query/MemberQueryService.java @@ -0,0 +1,8 @@ +package com.example.umc9th.domain.member.service.query; + +import com.example.umc9th.domain.member.dto.MemberReqDTO; +import com.example.umc9th.domain.member.dto.MemberResDTO; + +public interface MemberQueryService { + MemberResDTO.LoginDTO login(MemberReqDTO.LoginDTO dto); +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/query/MemberQueryServiceImpl.java b/src/main/java/com/example/umc9th/domain/member/service/query/MemberQueryServiceImpl.java new file mode 100644 index 0000000..29f2f63 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/query/MemberQueryServiceImpl.java @@ -0,0 +1,48 @@ +package com.example.umc9th.domain.member.service.query; + + +import com.example.umc9th.domain.member.converter.MemberConverter; +import com.example.umc9th.domain.member.dto.MemberReqDTO; +import com.example.umc9th.domain.member.dto.MemberResDTO; +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.global.jwt.JwtUtil; +import com.example.umc9th.global.security.CustomUserDetails; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class MemberQueryServiceImpl implements MemberQueryService{ + + private final MemberRepository memberRepository; + private final JwtUtil jwtUtil; + private final PasswordEncoder encoder; + + @Override + public MemberResDTO.LoginDTO login( + MemberReqDTO. LoginDTO dto + ) { + + // Member 조회 + Member member = memberRepository.findByEmailAndDeletedAtIsNull(dto.email()) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + // 비밀번호 검증 + if (!encoder.matches(dto.password(), member.getPassword())){ + throw new MemberException(MemberErrorCode.INVALID); + } + + // JWT 토큰 발급용 UserDetails + CustomUserDetails userDetails = new CustomUserDetails(member); + + // 엑세스 토큰 발급 + String accessToken = jwtUtil.createAccessToken(userDetails); + + // DTO 조립 + return MemberConverter.toLoginDTO(member, accessToken); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/controller/MemberMissionController.java b/src/main/java/com/example/umc9th/domain/mission/controller/MemberMissionController.java new file mode 100644 index 0000000..5a2b7d2 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/controller/MemberMissionController.java @@ -0,0 +1,48 @@ +package com.example.umc9th.domain.mission.controller; + +import com.example.umc9th.domain.mission.converter.MemberMissionConverter; +import com.example.umc9th.domain.mission.dto.MemberMissionResDTO; +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import com.example.umc9th.domain.mission.service.command.MemberMissionCommandService; +import com.example.umc9th.domain.mission.service.query.MemberMissionQueryService; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.domain.mission.exception.code.MissionSuccessCode; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +public class MemberMissionController implements MemberMissionControllerDocs{ + + private final MemberMissionCommandService memberMissionCommandService; + private final MemberMissionQueryService memberMissionQueryService; + + @PostMapping("/members/{memberId}/missions/{missionId}") + public ApiResponse challengeMission( + @PathVariable Long memberId, + @PathVariable Long missionId + ) { + MemberMission memberMission = + memberMissionCommandService.challengeMission(memberId, missionId); + + return ApiResponse.onSuccess( + MissionSuccessCode.CHALLENGED, + MemberMissionConverter.toChallengeDTO(memberMission) + ); + } + + // 진행 중인 미션 목록 조회 API + @GetMapping("/members/{memberId}/missions/ongoing") + public ApiResponse getOngoingMissions( + @PathVariable Long memberId, + @RequestParam @ValidPage Integer page + ) { + return ApiResponse.onSuccess( + MissionSuccessCode.MISSION_LIST_OK, + MemberMissionConverter.toChallengeListDTO( + memberMissionQueryService.findOngoingMissions(memberId, page) + ) + ); + } +} diff --git a/src/main/java/com/example/umc9th/domain/mission/controller/MemberMissionControllerDocs.java b/src/main/java/com/example/umc9th/domain/mission/controller/MemberMissionControllerDocs.java new file mode 100644 index 0000000..3262600 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/controller/MemberMissionControllerDocs.java @@ -0,0 +1,25 @@ +package com.example.umc9th.domain.mission.controller; + +import com.example.umc9th.domain.mission.dto.MemberMissionResDTO; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; + +public interface MemberMissionControllerDocs { + + @Operation( + summary = "진행중인 미션 목록 조회", + description = "회원이 진행 중인 미션을 페이지네이션으로 조회합니다." + ) + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") + }) + ApiResponse getOngoingMissions( + @PathVariable Long memberId, + @RequestParam @ValidPage Integer page + ); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/controller/MissionController.java b/src/main/java/com/example/umc9th/domain/mission/controller/MissionController.java new file mode 100644 index 0000000..1eeef77 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/controller/MissionController.java @@ -0,0 +1,40 @@ +package com.example.umc9th.domain.mission.controller; + +import com.example.umc9th.domain.mission.dto.MissionResDTO; +import com.example.umc9th.domain.mission.exception.code.MissionSuccessCode; +import com.example.umc9th.domain.mission.service.query.MissionQueryService; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.repository.StoreRepository; +import com.example.umc9th.domain.store.exception.StoreException; +import com.example.umc9th.domain.store.exception.code.StoreErrorCode; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +public class MissionController implements MissionControllerDocs { + + private final MissionQueryService missionQueryService; + private final StoreRepository storeRepository; + + @GetMapping("/missions") + public ApiResponse getMissionsByStore( + @RequestParam String storeName, + @RequestParam @ValidPage Integer page + ) { + // store 존재 여부 확인 + Store store = storeRepository.findByName(storeName) + .orElseThrow(() -> new StoreException(StoreErrorCode.NOT_FOUND)); + + // DTO 변환 + 성공 코드 포함 + return ApiResponse.onSuccess( + MissionSuccessCode.MISSION_LIST_OK, + missionQueryService.findMissionsByStore(store, page) + ); + } +} + diff --git a/src/main/java/com/example/umc9th/domain/mission/controller/MissionControllerDocs.java b/src/main/java/com/example/umc9th/domain/mission/controller/MissionControllerDocs.java new file mode 100644 index 0000000..c7e7222 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/controller/MissionControllerDocs.java @@ -0,0 +1,24 @@ +package com.example.umc9th.domain.mission.controller; + +import com.example.umc9th.domain.mission.dto.MissionResDTO; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import org.springframework.web.bind.annotation.RequestParam; + +public interface MissionControllerDocs { + + @Operation( + summary = "특정 가게 미션 목록 조회", + description = "특정 가게에 속한 미션 목록을 페이지네이션으로 조회합니다." + ) + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") + }) + ApiResponse getMissionsByStore( + @RequestParam String storeName, + @RequestParam @ValidPage Integer page + ); +} diff --git a/src/main/java/com/example/umc9th/domain/mission/converter/MemberMissionConverter.java b/src/main/java/com/example/umc9th/domain/mission/converter/MemberMissionConverter.java new file mode 100644 index 0000000..0bda5c4 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/converter/MemberMissionConverter.java @@ -0,0 +1,38 @@ +package com.example.umc9th.domain.mission.converter; + +import com.example.umc9th.domain.mission.dto.MemberMissionResDTO; +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import org.springframework.data.domain.Page; + +import java.util.stream.Collectors; + +public class MemberMissionConverter { + + // 미션 도전 후 DTO 변환 + public static MemberMissionResDTO.ChallengeDTO toChallengeDTO(MemberMission memberMission) { + return MemberMissionResDTO.ChallengeDTO.builder() + .memberMissionId(memberMission.getId()) + .missionId(memberMission.getMission().getId()) + .storeId(memberMission.getMission().getStore().getId()) + .storeName(memberMission.getMission().getStore().getName()) + .status(memberMission.getStatus()) + .deadline(memberMission.getMission().getDeadline()) + .point(memberMission.getMission().getPoint()) + .createdAt(memberMission.getCreatedAt()) + .build(); + } + + // 진행중 미션 목록 DTO 변환 + public static MemberMissionResDTO.ChallengeListDTO toChallengeListDTO(Page page) { + return MemberMissionResDTO.ChallengeListDTO.builder() + .missionList(page.getContent().stream() + .map(MemberMissionConverter::toChallengeDTO) + .collect(Collectors.toList())) + .listSize(page.getSize()) + .totalPage(page.getTotalPages()) + .totalElements(page.getTotalElements()) + .isFirst(page.isFirst()) + .isLast(page.isLast()) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/converter/MissionConverter.java b/src/main/java/com/example/umc9th/domain/mission/converter/MissionConverter.java new file mode 100644 index 0000000..fe23a29 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/converter/MissionConverter.java @@ -0,0 +1,34 @@ +package com.example.umc9th.domain.mission.converter; + +import com.example.umc9th.domain.mission.dto.MissionResDTO; +import com.example.umc9th.domain.mission.entity.Mission; +import org.springframework.data.domain.Page; + +public class MissionConverter { + + public static MissionResDTO.MissionPreviewListDTO toMissionPreviewListDTO(Page page) { + return MissionResDTO.MissionPreviewListDTO.builder() + .missionList( + page.getContent().stream() + .map(MissionConverter::toMissionPreviewDTO) + .toList() + ) + .listSize(page.getSize()) + .totalPage(page.getTotalPages()) + .totalElements(page.getTotalElements()) + .isFirst(page.isFirst()) + .isLast(page.isLast()) + .build(); + } + + public static MissionResDTO.MissionPreviewDTO toMissionPreviewDTO(Mission mission) { + return MissionResDTO.MissionPreviewDTO.builder() + .missionId(mission.getId()) + .storeName(mission.getStore().getName()) + .conditional(mission.getConditional()) + .point(mission.getPoint()) + .deadline(mission.getDeadline()) + .build(); + } +} + diff --git a/src/main/java/com/example/umc9th/domain/mission/dto/MemberMissionResDTO.java b/src/main/java/com/example/umc9th/domain/mission/dto/MemberMissionResDTO.java new file mode 100644 index 0000000..9e8bb5e --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/dto/MemberMissionResDTO.java @@ -0,0 +1,38 @@ +package com.example.umc9th.domain.mission.dto; + +import com.example.umc9th.domain.mission.enums.Status; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; +import java.util.List; + +public class MemberMissionResDTO { + + @Builder + @Getter + public static class ChallengeDTO { + private Long memberMissionId; + private Long missionId; + + private Long storeId; + private String storeName; + + private Status status; + private LocalDateTime deadline; + private Integer point; + + private LocalDateTime createdAt; + } + + @Builder + @Getter + public static class ChallengeListDTO { + private List missionList; + private int listSize; + private int totalPage; + private long totalElements; + private boolean isFirst; + private boolean isLast; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/dto/MissionResDTO.java b/src/main/java/com/example/umc9th/domain/mission/dto/MissionResDTO.java new file mode 100644 index 0000000..77e5486 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/dto/MissionResDTO.java @@ -0,0 +1,31 @@ +package com.example.umc9th.domain.mission.dto; + +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; +import java.util.List; + +public class MissionResDTO { + + @Getter + @Builder + public static class MissionPreviewDTO { + private Long missionId; + private String storeName; + private String conditional; + private Integer point; + private LocalDateTime deadline; + } + + @Getter + @Builder + public static class MissionPreviewListDTO { + private List missionList; + private int listSize; + private int totalPage; + private long totalElements; + private boolean isFirst; + private boolean isLast; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/entity/Mission.java b/src/main/java/com/example/umc9th/domain/mission/entity/Mission.java new file mode 100644 index 0000000..561bdba --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/entity/Mission.java @@ -0,0 +1,43 @@ +package com.example.umc9th.domain.mission.entity; + +import com.example.umc9th.domain.mission.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.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@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; + + // 하나의 미션은 특정 가게(Store)에 속함 + @ManyToOne(fetch = FetchType.LAZY,optional = false) + @JoinColumn(name = "store_id", nullable = false) + private Store store; + + @Column(name = "deadline", nullable = false) + private LocalDateTime deadline; + + @Column(name = "conditional", length = 255) + private String conditional; + + @Column(name = "point", nullable = false) + private Integer point; + + // 한 미션은 여러 회원-미션(MemberMission)을 가질 수 있음 + @OneToMany(mappedBy = "mission", cascade = CascadeType.ALL, orphanRemoval = true) + private List memberMissions = new ArrayList<>(); + +} diff --git a/src/main/java/com/example/umc9th/domain/mission/entity/mapping/MemberMission.java b/src/main/java/com/example/umc9th/domain/mission/entity/mapping/MemberMission.java new file mode 100644 index 0000000..8323107 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/entity/mapping/MemberMission.java @@ -0,0 +1,39 @@ +package com.example.umc9th.domain.mission.entity.mapping; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.mission.enums.Status; +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 = "member_mission", + uniqueConstraints = @UniqueConstraint(columnNames = {"member_id", "mission_id"}) +) +public class MemberMission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "status", nullable = false) + @Enumerated(EnumType.STRING) + private Status status; + + // 한 회원은 여러 미션을 수행할 수 있음 + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "member_id", nullable = false) + private Member member; + + // 한 미션은 여러 회원에게 부여될 수 있음 + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "mission_id", nullable = false) + private Mission mission; + +} diff --git a/src/main/java/com/example/umc9th/domain/mission/enums/Status.java b/src/main/java/com/example/umc9th/domain/mission/enums/Status.java new file mode 100644 index 0000000..d87e577 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/enums/Status.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.mission.enums; + +public enum Status { + ONGOING, COMPLETED, CANCELED; +} diff --git a/src/main/java/com/example/umc9th/domain/mission/exception/MemberMissionException.java b/src/main/java/com/example/umc9th/domain/mission/exception/MemberMissionException.java new file mode 100644 index 0000000..4166124 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/exception/MemberMissionException.java @@ -0,0 +1,10 @@ +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 MemberMissionException extends GeneralException { + public MemberMissionException(BaseErrorCode code) { + super(code); + } +} diff --git a/src/main/java/com/example/umc9th/domain/mission/exception/MissionException.java b/src/main/java/com/example/umc9th/domain/mission/exception/MissionException.java new file mode 100644 index 0000000..f3ad4c3 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/exception/MissionException.java @@ -0,0 +1,10 @@ +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); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/exception/code/MemberMissionErrorCode.java b/src/main/java/com/example/umc9th/domain/mission/exception/code/MemberMissionErrorCode.java new file mode 100644 index 0000000..1d97bbe --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/exception/code/MemberMissionErrorCode.java @@ -0,0 +1,20 @@ +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 MemberMissionErrorCode implements BaseErrorCode { + + ALREADY_CHALLENGED(HttpStatus.BAD_REQUEST, + "MEMBERMISSION400_1", + "이미 도전한 미션입니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} + diff --git a/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionErrorCode.java b/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionErrorCode.java new file mode 100644 index 0000000..0d38a45 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionErrorCode.java @@ -0,0 +1,22 @@ +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 { + + DEADLINE_EXPIRED(HttpStatus.BAD_REQUEST, + "MISSION400_2", + "이미 마감된 미션입니다."), + MISSION_NOT_FOUND(HttpStatus.NOT_FOUND, + "MISSION404_2", + "미션을 찾을 수 없습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java b/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java new file mode 100644 index 0000000..9493b7b --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java @@ -0,0 +1,18 @@ +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 { + + MISSION_LIST_OK(HttpStatus.OK, "MISSION200_1", "가게 미션 목록 조회 성공"), + CHALLENGED(HttpStatus.CREATED, "MISSION201_1", "미션에 성공적으로 도전했습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/mission/repository/MemberMissionRepository.java b/src/main/java/com/example/umc9th/domain/mission/repository/MemberMissionRepository.java new file mode 100644 index 0000000..f70fa5d --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/repository/MemberMissionRepository.java @@ -0,0 +1,27 @@ +package com.example.umc9th.domain.mission.repository; + +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import com.example.umc9th.domain.mission.enums.Status; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MemberMissionRepository extends JpaRepository { + + // 페이징과 함께 mission, mission.store를 함께 로드하도록 EntityGraph 사용 + @EntityGraph(attributePaths = {"mission", "mission.store"}) + Page findByMember_IdAndStatusOrderByMission_DeadlineAsc(Long memberId, Status status, Pageable pageable); + + // 진행중(ONGOING) / 완료(COMPLETED) 조회 + default Page findOngoingMissionsByMemberId(Long memberId, Pageable pageable) { + return findByMember_IdAndStatusOrderByMission_DeadlineAsc(memberId, Status.ONGOING, pageable); + } + + default Page findCompletedMissionsByMemberId(Long memberId, Pageable pageable) { + return findByMember_IdAndStatusOrderByMission_DeadlineAsc(memberId, Status.COMPLETED, pageable); + } + + // 이미 도전했는지 확인용 메서드 + boolean existsByMember_IdAndMission_Id(Long memberId, Long missionId); +} diff --git a/src/main/java/com/example/umc9th/domain/mission/repository/MissionRepository.java b/src/main/java/com/example/umc9th/domain/mission/repository/MissionRepository.java new file mode 100644 index 0000000..cdc7b83 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/repository/MissionRepository.java @@ -0,0 +1,54 @@ +package com.example.umc9th.domain.mission.repository; + +import com.example.umc9th.domain.member.enums.Address; +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.store.entity.Store; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.time.LocalDateTime; + +public interface MissionRepository extends JpaRepository { + + // 홈 화면 — 현재 선택된 지역에서 도전 가능한 미션 목록 조회 (비로그인) / N + 1 방지 + @EntityGraph(attributePaths = {"store", "store.location"}) + @Query(""" + SELECT m + FROM Mission m + WHERE m.store.location.address = :address + AND m.deadline > :now + ORDER BY m.deadline ASC + """) + Page findAvailableMissionsByLocation( + @Param("address") Address address, + @Param("now") LocalDateTime now, + Pageable pageable + ); + + // 홈 — 특정 멤버가 이미 완료한 미션을 제외한 현재 선택된 지역의 미션 목록 (로그인한 회원) / N + 1 방지 + @EntityGraph(attributePaths = {"store", "store.location"}) + @Query(""" + SELECT m + FROM Mission m + LEFT JOIN MemberMission mm + ON mm.mission = m AND mm.member.id = :memberId + WHERE m.store.location.address = :address + AND m.deadline > :now + AND (mm IS NULL OR mm.status <> com.example.umc9th.domain.mission.enums.Status.COMPLETED) + ORDER BY m.deadline ASC + """) + Page findAvailableMissionsByLocationExcludingMemberCompleted( + @Param("memberId") Long memberId, + @Param("address") Address address, + @Param("now") LocalDateTime now, + Pageable pageable + ); + + @EntityGraph(attributePaths = {"store"}) + Page findAllByStore(Store store, Pageable pageable); + +} diff --git a/src/main/java/com/example/umc9th/domain/mission/service/command/MemberMissionCommandService.java b/src/main/java/com/example/umc9th/domain/mission/service/command/MemberMissionCommandService.java new file mode 100644 index 0000000..4c1fa76 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/command/MemberMissionCommandService.java @@ -0,0 +1,56 @@ +package com.example.umc9th.domain.mission.service.command; + +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.mission.entity.Mission; +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import com.example.umc9th.domain.mission.enums.Status; +import com.example.umc9th.domain.mission.exception.MemberMissionException; +import com.example.umc9th.domain.mission.exception.MissionException; +import com.example.umc9th.domain.mission.exception.code.MemberMissionErrorCode; +import com.example.umc9th.domain.mission.exception.code.MissionErrorCode; +import com.example.umc9th.domain.mission.repository.MemberMissionRepository; +import com.example.umc9th.domain.mission.repository.MissionRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +public class MemberMissionCommandService { + + private final MemberMissionRepository memberMissionRepository; + private final MissionRepository missionRepository; + private final MemberRepository memberRepository; + + @Transactional + public MemberMission challengeMission(Long memberId, Long missionId) { + + Member member = memberRepository.findById(memberId) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + Mission mission = missionRepository.findById(missionId) + .orElseThrow(() -> new MissionException(MissionErrorCode.MISSION_NOT_FOUND)); + + if (mission.getDeadline().isBefore(LocalDateTime.now())) { + throw new MissionException(MissionErrorCode.DEADLINE_EXPIRED); + } + + if (memberMissionRepository.existsByMember_IdAndMission_Id(memberId, missionId)) + throw new MemberMissionException(MemberMissionErrorCode.ALREADY_CHALLENGED); + + MemberMission memberMission = MemberMission.builder() + .member(member) + .mission(mission) + .status(Status.ONGOING) + .build(); + + return memberMissionRepository.save(memberMission); + } + + +} diff --git a/src/main/java/com/example/umc9th/domain/mission/service/query/MemberMissionQueryService.java b/src/main/java/com/example/umc9th/domain/mission/service/query/MemberMissionQueryService.java new file mode 100644 index 0000000..f9d7647 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/query/MemberMissionQueryService.java @@ -0,0 +1,10 @@ +package com.example.umc9th.domain.mission.service.query; + +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import org.springframework.data.domain.Page; + +public interface MemberMissionQueryService { + + // 진행중인 미션 조회 + Page findOngoingMissions(Long memberId, Integer page); +} diff --git a/src/main/java/com/example/umc9th/domain/mission/service/query/MemberMissionQueryServiceImpl.java b/src/main/java/com/example/umc9th/domain/mission/service/query/MemberMissionQueryServiceImpl.java new file mode 100644 index 0000000..4d46c69 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/query/MemberMissionQueryServiceImpl.java @@ -0,0 +1,22 @@ +package com.example.umc9th.domain.mission.service.query; + +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import com.example.umc9th.domain.mission.repository.MemberMissionRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class MemberMissionQueryServiceImpl implements MemberMissionQueryService { + + private final MemberMissionRepository memberMissionRepository; + + @Override + public Page findOngoingMissions(Long memberId, Integer page) { + PageRequest pageRequest = PageRequest.of(page - 1, 10); + return memberMissionRepository.findOngoingMissionsByMemberId(memberId, pageRequest); + } + +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/service/query/MissionQueryService.java b/src/main/java/com/example/umc9th/domain/mission/service/query/MissionQueryService.java new file mode 100644 index 0000000..be5f8fe --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/query/MissionQueryService.java @@ -0,0 +1,8 @@ +package com.example.umc9th.domain.mission.service.query; + +import com.example.umc9th.domain.mission.dto.MissionResDTO; +import com.example.umc9th.domain.store.entity.Store; + +public interface MissionQueryService { + MissionResDTO.MissionPreviewListDTO findMissionsByStore(Store store, int page); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/service/query/MissionQueryServiceImpl.java b/src/main/java/com/example/umc9th/domain/mission/service/query/MissionQueryServiceImpl.java new file mode 100644 index 0000000..21c0608 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/query/MissionQueryServiceImpl.java @@ -0,0 +1,30 @@ +package com.example.umc9th.domain.mission.service.query; + +import com.example.umc9th.domain.mission.converter.MissionConverter; +import com.example.umc9th.domain.mission.dto.MissionResDTO; +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.mission.repository.MissionRepository; +import com.example.umc9th.domain.store.entity.Store; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class MissionQueryServiceImpl implements MissionQueryService { + + private final MissionRepository missionRepository; + + @Override + public MissionResDTO.MissionPreviewListDTO findMissionsByStore(Store store, int page) { + // page 1 이상 보장, 한 페이지 10개 + PageRequest pageRequest = PageRequest.of(page - 1, 10); + + // Mission 목록 조회 + Page result = missionRepository.findAllByStore(store, pageRequest); + + // DTO 변환 + return MissionConverter.toMissionPreviewListDTO(result); + } +} diff --git a/src/main/java/com/example/umc9th/domain/review/controller/ReviewController.java b/src/main/java/com/example/umc9th/domain/review/controller/ReviewController.java new file mode 100644 index 0000000..b1cdee4 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/controller/ReviewController.java @@ -0,0 +1,59 @@ +package com.example.umc9th.domain.review.controller; + +import com.example.umc9th.domain.review.converter.ReviewConverter; +import com.example.umc9th.domain.review.dto.ReviewReqDTO; +import com.example.umc9th.domain.review.dto.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.command.ReviewCommandService; +import com.example.umc9th.domain.review.service.query.ReviewQueryService; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +public class ReviewController implements ReviewControllerDocs{ + + private final ReviewQueryService reviewQueryService; + private final ReviewCommandService reviewCommandService; + + // 내 리뷰 조회 + 필터링 (페이징) + @GetMapping("/reviews/my") + public ApiResponse getMyReviews( + @RequestParam Long memberId, + @RequestParam(required = false) String storeName, + @RequestParam(required = false) Integer star, + @RequestParam @ValidPage Integer page + ) { + ReviewSuccessCode code = ReviewSuccessCode.REVIEW_LIST_OK; + return ApiResponse.onSuccess(code, reviewQueryService.findMyReviews(memberId, storeName, star, page)); + } + + + // 가게에 리뷰 추가하기 + @PostMapping("/stores/{storeId}/reviews") + public ApiResponse createReview( + @PathVariable Long storeId, + @RequestBody @Valid ReviewReqDTO.CreateDTO dto + ) { + Review review = reviewCommandService.createReview(dto, storeId); + + return ApiResponse.onSuccess( + ReviewSuccessCode.CREATED, + ReviewConverter.toCreateDTO(review) + ); + } + + // 가게의 리뷰 목록 조회 + @GetMapping("/reviews") + public ApiResponse getReviews( + @RequestParam String storeName, + @RequestParam @ValidPage Integer page + ){ + ReviewSuccessCode code = ReviewSuccessCode.REVIEW_LIST_OK; + return ApiResponse.onSuccess(code, reviewQueryService.findReview(storeName, page)); + } +} diff --git a/src/main/java/com/example/umc9th/domain/review/controller/ReviewControllerDocs.java b/src/main/java/com/example/umc9th/domain/review/controller/ReviewControllerDocs.java new file mode 100644 index 0000000..103a6f8 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/controller/ReviewControllerDocs.java @@ -0,0 +1,36 @@ +package com.example.umc9th.domain.review.controller; + +import com.example.umc9th.domain.review.dto.ReviewResDTO; +import com.example.umc9th.global.annotation.ValidPage; +import com.example.umc9th.global.apiPayload.ApiResponse; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import org.springframework.web.bind.annotation.RequestParam; + +public interface ReviewControllerDocs { + + @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 = "실패") + }) + ApiResponse getReviews( + @RequestParam String storeName, + @RequestParam @ValidPage Integer page + ); + + @Operation(summary = "내 리뷰 조회", description = "특정 회원의 리뷰를 페이지네이션으로 조회합니다.") + @ApiResponses({ + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "성공"), + @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "실패") + }) + ApiResponse getMyReviews( + @RequestParam Long memberId, + @RequestParam(required = false) String storeName, + @RequestParam(required = false) Integer star, + @RequestParam @ValidPage Integer page + ); +} diff --git a/src/main/java/com/example/umc9th/domain/review/converter/ReviewConverter.java b/src/main/java/com/example/umc9th/domain/review/converter/ReviewConverter.java new file mode 100644 index 0000000..7078cf1 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/converter/ReviewConverter.java @@ -0,0 +1,46 @@ +package com.example.umc9th.domain.review.converter; + +import com.example.umc9th.domain.review.dto.ReviewResDTO; +import com.example.umc9th.domain.review.entity.Review; +import org.springframework.data.domain.Page; + +public class ReviewConverter { + + // Review 엔티티를 리뷰 생성 응답 DTO로 변환하는 메서드 + public static ReviewResDTO.CreateDTO toCreateDTO(Review review) { + return ReviewResDTO.CreateDTO.builder() + .reviewId(review.getId()) + .storeId(review.getStore().getId()) + .storeName(review.getStore().getName()) + .createdAt(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.getNumberOfElements()) + .totalPage(result.getTotalPages()) + .totalElements(result.getTotalElements()) + .isFirst(result.isFirst()) + .isLast(result.isLast()) + .build(); + } + + public static ReviewResDTO.ReviewPreViewDTO toReviewPreviewDTO( + Review review + ){ + return ReviewResDTO.ReviewPreViewDTO.builder() + .memberNickname(review.getMember().getNickname()) + .star(review.getStar()) + .content(review.getContent()) + .createdAt(review.getCreatedAt()) + .build(); + } +} diff --git a/src/main/java/com/example/umc9th/domain/review/dto/ReviewReqDTO.java b/src/main/java/com/example/umc9th/domain/review/dto/ReviewReqDTO.java new file mode 100644 index 0000000..8a2c088 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/dto/ReviewReqDTO.java @@ -0,0 +1,22 @@ +package com.example.umc9th.domain.review.dto; + +import jakarta.validation.constraints.*; +import java.util.List; + +public class ReviewReqDTO { + + public record CreateDTO( + + @NotNull(message = "회원 ID는 필수입니다.") + Long memberId, + + @NotNull(message = "별점은 필수입니다.") + @DecimalMin(value = "0.5", message = "별점은 최소 0.5 이상이어야 합니다.") + @DecimalMax(value = "5.0", message = "별점은 최대 5.0 이하여야 합니다.") + Float star, + + @NotBlank(message = "리뷰 내용은 필수입니다.") + String content + + ) {} +} diff --git a/src/main/java/com/example/umc9th/domain/review/dto/ReviewResDTO.java b/src/main/java/com/example/umc9th/domain/review/dto/ReviewResDTO.java new file mode 100644 index 0000000..9fa994b --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/dto/ReviewResDTO.java @@ -0,0 +1,49 @@ +package com.example.umc9th.domain.review.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; +import java.util.List; + +public class ReviewResDTO { + + @Builder + @Getter + public static class MyReviewPreview { + private Long reviewId; + private String storeName; + private String content; + private Float star; + private LocalDateTime createdAt; + } + + @Builder + @Getter + public static class CreateDTO { + private Long reviewId; + private Long storeId; + private String storeName; + private LocalDateTime createdAt; + } + + @Builder + public record ReviewPreViewListDTO( + List reviewList, + Integer listSize, + Integer totalPage, + Long totalElements, + Boolean isFirst, + Boolean isLast + ){} + + @Builder + public record ReviewPreViewDTO( + String memberNickname, + Float star, + String content, + LocalDateTime createdAt + ){} +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/entity/Reply.java b/src/main/java/com/example/umc9th/domain/review/entity/Reply.java new file mode 100644 index 0000000..7c313bc --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/entity/Reply.java @@ -0,0 +1,31 @@ +package com.example.umc9th.domain.review.entity; + +import com.example.umc9th.domain.member.entity.Member; +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "reply") +public class Reply { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "content", nullable = false, length = 500) + private String content; + + //어떤 리뷰에 달린 댓글인지 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "review_id", nullable = false) + private Review review; + + //댓글 작성자 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id", nullable = false) + private Member member; +} diff --git a/src/main/java/com/example/umc9th/domain/review/entity/Review.java b/src/main/java/com/example/umc9th/domain/review/entity/Review.java new file mode 100644 index 0000000..2f0bb70 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/entity/Review.java @@ -0,0 +1,47 @@ +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.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@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; + + // 한 명의 회원은 여러 리뷰를 작성할 수 있음 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id", nullable = false) + private Member member; + + // 하나의 가게에는 여러 리뷰가 달릴 수 있음 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id", nullable = false) + private Store store; + + @Column(name = "star", nullable = false) + private float star; + + @Column(name = "content", nullable = false, length = 1000) + private String content; + + // 리뷰에 달린 댓글 + @OneToMany(mappedBy = "review", cascade = CascadeType.ALL, orphanRemoval = true) + private List replyList = new ArrayList<>(); + + @OneToMany(mappedBy = "review", cascade = CascadeType.ALL, orphanRemoval = true) + private List reviewPhotoList = new ArrayList<>(); +} diff --git a/src/main/java/com/example/umc9th/domain/review/entity/ReviewPhoto.java b/src/main/java/com/example/umc9th/domain/review/entity/ReviewPhoto.java new file mode 100644 index 0000000..f2e1884 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/entity/ReviewPhoto.java @@ -0,0 +1,25 @@ +package com.example.umc9th.domain.review.entity; + +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "review_photo") +public class ReviewPhoto { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "photo_url", nullable = false, length = 300) + private String photoUrl; + + // 어떤 리뷰의 사진인지 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "review_id", nullable = false) + private Review review; +} diff --git a/src/main/java/com/example/umc9th/domain/review/exception/ReviewException.java b/src/main/java/com/example/umc9th/domain/review/exception/ReviewException.java new file mode 100644 index 0000000..afde6b0 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewErrorCode.java b/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewErrorCode.java new file mode 100644 index 0000000..6bc9863 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewErrorCode.java @@ -0,0 +1,19 @@ +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_NOT_FOUND(HttpStatus.NOT_FOUND, + "REVIEW404_1", + "해당 리뷰를 찾을 수 없습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewSuccessCode.java b/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewSuccessCode.java new file mode 100644 index 0000000..ee2ac65 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewSuccessCode.java @@ -0,0 +1,23 @@ +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 { + + REVIEW_LIST_OK(HttpStatus.OK, + "REVIEW200_1", + "리뷰 목록 조회 성공"), + CREATED(HttpStatus.CREATED, + "REVIEW201_1", + "리뷰가 성공적으로 등록되었습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/review/repository/ReviewRepository.java b/src/main/java/com/example/umc9th/domain/review/repository/ReviewRepository.java new file mode 100644 index 0000000..9cffc60 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/repository/ReviewRepository.java @@ -0,0 +1,26 @@ +package com.example.umc9th.domain.review.repository; + +import com.example.umc9th.domain.member.entity.Member; +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.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface ReviewRepository extends JpaRepository, ReviewQueryDsl { + + // 특정 가게(Store)에 작성된 모든 리뷰 (삭제되지 않은 것만) + List findByStoreAndDeletedAtIsNull(Store store); + + // 특정 회원(Member)이 작성한 리뷰 (마이페이지용) + List findByMemberAndDeletedAtIsNull(Member member); + + // 닉네임으로 리뷰 조회 (가게 관리자 페이지에서 검색 가능) + List findByMember_NicknameAndDeletedAtIsNull(String nickname); + + // 가게 리뷰 페이징 조회 + Page findAllByStoreAndDeletedAtIsNull(Store store, Pageable pageable); +} diff --git a/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDsl.java b/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDsl.java new file mode 100644 index 0000000..0a1ba08 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDsl.java @@ -0,0 +1,13 @@ +package com.example.umc9th.domain.review.repository.querydsl; + +import com.example.umc9th.domain.review.entity.Review; +import com.querydsl.core.types.Predicate; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + + +public interface ReviewQueryDsl { + + // Predicate + Pageable 기반 동적 쿼리 + Page searchReviews(Predicate predicate, Pageable pageable); +} diff --git a/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDslImpl.java b/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDslImpl.java new file mode 100644 index 0000000..66527b1 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/repository/querydsl/ReviewQueryDslImpl.java @@ -0,0 +1,49 @@ +package com.example.umc9th.domain.review.repository.querydsl; + +import com.example.umc9th.domain.review.entity.QReply; +import com.example.umc9th.domain.review.entity.QReview; +import com.example.umc9th.domain.review.entity.QReviewPhoto; +import com.example.umc9th.domain.review.entity.Review; +import com.querydsl.core.types.Predicate; +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +@RequiredArgsConstructor +public class ReviewQueryDslImpl implements ReviewQueryDsl { + + private final EntityManager em; + + @Override + public Page searchReviews(Predicate predicate, Pageable pageable) { + JPAQueryFactory queryFactory = new JPAQueryFactory(em); + QReview review = QReview.review; + + // 필터링된 리뷰 조회 + List results = queryFactory + .selectFrom(review) + .where(predicate) + .orderBy(review.createdAt.desc()) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .fetch(); + + // 전체 개수 계산 (count 쿼리) + Long total = Optional.ofNullable( + queryFactory.select(review.count()) + .from(review) + .where(predicate) + .fetchOne() + ).orElse(0L); + + return new PageImpl<>(results, pageable, total); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/service/command/ReviewCommandService.java b/src/main/java/com/example/umc9th/domain/review/service/command/ReviewCommandService.java new file mode 100644 index 0000000..e69b911 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/service/command/ReviewCommandService.java @@ -0,0 +1,50 @@ +package com.example.umc9th.domain.review.service.command; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.review.dto.ReviewReqDTO; +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.repository.StoreRepository; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import static com.example.umc9th.domain.member.exception.code.MemberErrorCode.MEMBER_NOT_FOUND; +import static com.example.umc9th.domain.store.exception.code.StoreErrorCode.NOT_FOUND; + + +@Service +@RequiredArgsConstructor +public class ReviewCommandService { + + private final ReviewRepository reviewRepository; + private final StoreRepository storeRepository; + private final MemberRepository memberRepository; + + @Transactional + public Review createReview(ReviewReqDTO.CreateDTO dto, Long storeId) { + + // 회원 검증 + Member member = memberRepository.findById(dto.memberId()) + .orElseThrow(() -> new MemberException(MEMBER_NOT_FOUND)); + + // 가게 검증 + Store store = storeRepository.findById(storeId) + .orElseThrow(() -> new StoreException(NOT_FOUND)); + + // 리뷰 생성 + Review review = Review.builder() + .member(member) + .store(store) + .star(dto.star()) + .content(dto.content()) + .build(); + + return reviewRepository.saveAndFlush(review); + } +} + diff --git a/src/main/java/com/example/umc9th/domain/review/service/query/ReviewQueryService.java b/src/main/java/com/example/umc9th/domain/review/service/query/ReviewQueryService.java new file mode 100644 index 0000000..9e4ba6f --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/service/query/ReviewQueryService.java @@ -0,0 +1,9 @@ +package com.example.umc9th.domain.review.service.query; + +import com.example.umc9th.domain.review.dto.ReviewResDTO; + +public interface ReviewQueryService { + ReviewResDTO.ReviewPreViewListDTO findMyReviews(Long memberId, String storeName, Integer star, Integer page); + + ReviewResDTO.ReviewPreViewListDTO findReview(String storeName, Integer page); +} diff --git a/src/main/java/com/example/umc9th/domain/review/service/query/ReviewQueryServiceImpl.java b/src/main/java/com/example/umc9th/domain/review/service/query/ReviewQueryServiceImpl.java new file mode 100644 index 0000000..f99523d --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/service/query/ReviewQueryServiceImpl.java @@ -0,0 +1,84 @@ +package com.example.umc9th.domain.review.service.query; + +import com.example.umc9th.domain.review.converter.ReviewConverter; +import com.example.umc9th.domain.review.dto.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.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; + +@Service +@RequiredArgsConstructor +public class ReviewQueryServiceImpl implements ReviewQueryService{ + + private final ReviewRepository reviewRepository; + private final StoreRepository storeRepository; + + @Override + public ReviewResDTO.ReviewPreViewListDTO findMyReviews( + Long memberId, + String storeName, + Integer star, + Integer page + ) { + PageRequest pageRequest = PageRequest.of(page - 1, 10); + + QReview review = QReview.review; + BooleanBuilder builder = new BooleanBuilder(); + + // 필수: memberId + builder.and(review.member.id.eq(memberId)); + + // optional: storeName + if (storeName != null && !storeName.isEmpty()) { + builder.and(review.store.name.containsIgnoreCase(storeName)); + } + + // optional: star + if (star != null) { + if (star == 5) { + builder.and(review.star.eq(5.0f)); + } else { + float min = star.floatValue(); + float max = star + 0.9f; + builder.and(review.star.between(min, max)); + } + } + + // 삭제된 리뷰 제외 + builder.and(review.deletedAt.isNull()); + + // 검색 수행 + Page result = reviewRepository.searchReviews(builder, pageRequest); + + // DTO 변환 + return ReviewConverter.toReviewPreviewListDTO(result); + } + + + @Override + public ReviewResDTO.ReviewPreViewListDTO findReview( + String storeName, + Integer page + ){ + // - 가게를 가져온다 (가게 존재 여부 검증) + Store store = storeRepository.findByName(storeName) + // - 없으면 예외 터뜨린다 + .orElseThrow(() -> new StoreException(StoreErrorCode.NOT_FOUND)); + + //- 가게에 맞는 리뷰를 가져온다 (Offset 페이징) + PageRequest pageRequest = PageRequest.of(page -1, 10); + Page result = reviewRepository.findAllByStoreAndDeletedAtIsNull(store, pageRequest); + + //- 결과를 응답 DTO로 변환한다 (컨버터 이용) + return ReviewConverter.toReviewPreviewListDTO(result); + } +} diff --git a/src/main/java/com/example/umc9th/domain/store/entity/Location.java b/src/main/java/com/example/umc9th/domain/store/entity/Location.java new file mode 100644 index 0000000..a7e0fa0 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/entity/Location.java @@ -0,0 +1,29 @@ +package com.example.umc9th.domain.store.entity; + +import com.example.umc9th.domain.member.enums.Address; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "location") +public class Location { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", nullable = false, length = 30) + @Enumerated(EnumType.STRING) + private Address address; + + // 한 지역에는 여러 가게가 존재 + @OneToMany(mappedBy = "location", cascade = CascadeType.ALL, orphanRemoval = true) + private List stores = new ArrayList<>(); +} diff --git a/src/main/java/com/example/umc9th/domain/store/entity/Store.java b/src/main/java/com/example/umc9th/domain/store/entity/Store.java new file mode 100644 index 0000000..2f35837 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/entity/Store.java @@ -0,0 +1,41 @@ +package com.example.umc9th.domain.store.entity; + +import com.example.umc9th.domain.store.entity.mapping.MemberFoodStore; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@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, length = 50) + private String name; + + @Column(name = "address_detail", nullable = false, length = 255) + private String addressDetail; + + // 어느 지역에 속한 가게인지 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "location_id", nullable = false) + private Location location; + + @Column(name = "manager_num", nullable = false) + private Integer managerNum; + + // 사용자 선호 음식별 가게 매핑 + @OneToMany(mappedBy = "store", cascade = CascadeType.ALL, orphanRemoval = true) + private List memberFoodStores = new ArrayList<>(); + +} diff --git a/src/main/java/com/example/umc9th/domain/store/entity/mapping/MemberFoodStore.java b/src/main/java/com/example/umc9th/domain/store/entity/mapping/MemberFoodStore.java new file mode 100644 index 0000000..969be35 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/entity/mapping/MemberFoodStore.java @@ -0,0 +1,33 @@ +package com.example.umc9th.domain.store.entity.mapping; + +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import com.example.umc9th.domain.store.entity.Store; +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table( + name = "member_food_store", + uniqueConstraints = @UniqueConstraint(columnNames = {"store_id", "member_food_id"}) +) +public class MemberFoodStore { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // 어떤 가게와 연결되어 있는지 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id", nullable = false) + private Store store; + + //어떤 회원의 음식 취향과 연결되어 있는지 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_food_id", nullable = false) + private MemberFood memberFood; + +} diff --git a/src/main/java/com/example/umc9th/domain/store/exception/StoreException.java b/src/main/java/com/example/umc9th/domain/store/exception/StoreException.java new file mode 100644 index 0000000..13de034 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/store/exception/code/StoreErrorCode.java b/src/main/java/com/example/umc9th/domain/store/exception/code/StoreErrorCode.java new file mode 100644 index 0000000..4ef4c78 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/exception/code/StoreErrorCode.java @@ -0,0 +1,19 @@ +package com.example.umc9th.domain.store.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum StoreErrorCode implements BaseErrorCode { + + NOT_FOUND(HttpStatus.NOT_FOUND, + "STORE404_1", + "해당 가게를 찾을 수 없습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/store/exception/code/StoreSuccessCode.java b/src/main/java/com/example/umc9th/domain/store/exception/code/StoreSuccessCode.java new file mode 100644 index 0000000..b7df137 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/exception/code/StoreSuccessCode.java @@ -0,0 +1,19 @@ +package com.example.umc9th.domain.store.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseSuccessCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum StoreSuccessCode implements BaseSuccessCode { + + STORE_FOUND(HttpStatus.OK, + "STORE200_1", + "가게 정보 조회 성공."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/store/repository/StoreRepository.java b/src/main/java/com/example/umc9th/domain/store/repository/StoreRepository.java new file mode 100644 index 0000000..c447562 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/repository/StoreRepository.java @@ -0,0 +1,14 @@ +package com.example.umc9th.domain.store.repository; + +import com.example.umc9th.domain.store.entity.Store; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface StoreRepository extends JpaRepository { + + // 가게 존재 여부 확인 + Optional findByName(String name); +} diff --git a/src/main/java/com/example/umc9th/domain/test/controller/TestController.java b/src/main/java/com/example/umc9th/domain/test/controller/TestController.java new file mode 100644 index 0000000..1f6438f --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/controller/TestController.java @@ -0,0 +1,38 @@ +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.exception.TestException; +import com.example.umc9th.domain.test.service.query.TestQueryService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralErrorCode; +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() { + //응답 코드 정의 + 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!")); + } +} diff --git a/src/main/java/com/example/umc9th/domain/test/converter/TestConverter.java b/src/main/java/com/example/umc9th/domain/test/converter/TestConverter.java new file mode 100644 index 0000000..d0dc9b8 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/converter/TestConverter.java @@ -0,0 +1,20 @@ +package com.example.umc9th.domain.test.converter; + +import com.example.umc9th.domain.test.dto.res.TestResDTO; + +public class TestConverter { + + // 객체 -> DTO + public static TestResDTO.Testing toTestingDTO(String testing){ + return TestResDTO.Testing.builder() + .testing(testing) + .build(); + } + + // 객체 -> DTO + public static TestResDTO.Exception toExceptionDTO(String testing){ + return TestResDTO.Exception.builder() + .testString(testing) + .build(); + } +} diff --git a/src/main/java/com/example/umc9th/domain/test/dto/req/TestReqDTO.java b/src/main/java/com/example/umc9th/domain/test/dto/req/TestReqDTO.java new file mode 100644 index 0000000..405e3b9 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/dto/req/TestReqDTO.java @@ -0,0 +1,4 @@ +package com.example.umc9th.domain.test.dto.req; + +public class TestReqDTO { +} diff --git a/src/main/java/com/example/umc9th/domain/test/dto/res/TestResDTO.java b/src/main/java/com/example/umc9th/domain/test/dto/res/TestResDTO.java new file mode 100644 index 0000000..47dcbc4 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/dto/res/TestResDTO.java @@ -0,0 +1,19 @@ +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/src/main/java/com/example/umc9th/domain/test/exception/TestException.java b/src/main/java/com/example/umc9th/domain/test/exception/TestException.java new file mode 100644 index 0000000..1faf200 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/test/exception/code/TestErrorCode.java b/src/main/java/com/example/umc9th/domain/test/exception/code/TestErrorCode.java new file mode 100644 index 0000000..9fe17e7 --- /dev/null +++ b/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 { + // For test + TEST_EXCEPTION(HttpStatus.BAD_REQUEST, "TEST400_1", "이거는 테스트"), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandService.java b/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandService.java new file mode 100644 index 0000000..b1102dd --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandServiceImpl.java b/src/main/java/com/example/umc9th/domain/test/service/command/TestCommandServiceImpl.java new file mode 100644 index 0000000..3e5a276 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryService.java b/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryService.java new file mode 100644 index 0000000..2163565 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryService.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.test.service.query; + +public interface TestQueryService { + void checkFlag(Long flag); +} diff --git a/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryServiceImpl.java b/src/main/java/com/example/umc9th/domain/test/service/query/TestQueryServiceImpl.java new file mode 100644 index 0000000..17ff689 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/global/annotation/ExistFoods.java b/src/main/java/com/example/umc9th/global/annotation/ExistFoods.java new file mode 100644 index 0000000..b5c8041 --- /dev/null +++ b/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/src/main/java/com/example/umc9th/global/annotation/ValidPage.java b/src/main/java/com/example/umc9th/global/annotation/ValidPage.java new file mode 100644 index 0000000..ca7f67a --- /dev/null +++ b/src/main/java/com/example/umc9th/global/annotation/ValidPage.java @@ -0,0 +1,17 @@ +package com.example.umc9th.global.annotation; + +import com.example.umc9th.global.validator.ValidPageValidator; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.*; + +@Documented +@Constraint(validatedBy = ValidPageValidator.class) +@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ValidPage { + String message() default "유효하지 않은 페이지 번호입니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java b/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java new file mode 100644 index 0000000..9322ea0 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java @@ -0,0 +1,41 @@ +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 T result; + + // 성공한 경우 (result 포함) + public static ApiResponse onSuccess(BaseSuccessCode code, T result) { + return new ApiResponse(true, code.getCode(), code.getMessage(), result); + } + + // 성공한 경우 (result 없음) + public static ApiResponse onSuccess(BaseSuccessCode code) { + return new ApiResponse<>(true, code.getCode(), code.getMessage(), null); + } + + // 실패한 경우 (result 포함) + public static ApiResponse onFailure(BaseErrorCode code, T result) { + return new ApiResponse<>(false, code.getCode(), code.getMessage(), result); + } +} diff --git a/src/main/java/com/example/umc9th/global/apiPayload/code/BaseErrorCode.java b/src/main/java/com/example/umc9th/global/apiPayload/code/BaseErrorCode.java new file mode 100644 index 0000000..d0d553f --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/code/BaseErrorCode.java @@ -0,0 +1,10 @@ +package com.example.umc9th.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseErrorCode { + + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} diff --git a/src/main/java/com/example/umc9th/global/apiPayload/code/BaseSuccessCode.java b/src/main/java/com/example/umc9th/global/apiPayload/code/BaseSuccessCode.java new file mode 100644 index 0000000..fb269df --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/code/BaseSuccessCode.java @@ -0,0 +1,10 @@ +package com.example.umc9th.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseSuccessCode { + + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} diff --git a/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralErrorCode.java b/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralErrorCode.java new file mode 100644 index 0000000..6222e7f --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralErrorCode.java @@ -0,0 +1,36 @@ +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, + "COMMON400_2", + "유효성 검사에 실패했습니다."), + INVALID_REQUEST(HttpStatus.BAD_REQUEST, + "COMMON400_3", + "잘못된 페이지 번호 요청입니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralSuccessCode.java b/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralSuccessCode.java new file mode 100644 index 0000000..f7bc5fd --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralSuccessCode.java @@ -0,0 +1,27 @@ +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", + "성공적으로 요청을 처리했습니다."), + CREATED(HttpStatus.CREATED, + "COMMON201", + "리소스가 성공적으로 생성되었습니다."), + ACCEPTED(HttpStatus.ACCEPTED, + "COMMON202", + "요청이 접수되었습니다."), + NO_CONTENT(HttpStatus.NO_CONTENT, + "COMMON204", + "성공했지만 반환할 내용이 없습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc9th/global/apiPayload/exception/GeneralException.java b/src/main/java/com/example/umc9th/global/apiPayload/exception/GeneralException.java new file mode 100644 index 0000000..bd7517f --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/exception/GeneralException.java @@ -0,0 +1,12 @@ +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/src/main/java/com/example/umc9th/global/apiPayload/exception/PageNumberException.java b/src/main/java/com/example/umc9th/global/apiPayload/exception/PageNumberException.java new file mode 100644 index 0000000..87d0119 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/exception/PageNumberException.java @@ -0,0 +1,8 @@ +package com.example.umc9th.global.apiPayload.exception; + +public class PageNumberException extends RuntimeException { + + public PageNumberException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java b/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java new file mode 100644 index 0000000..77fa459 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java @@ -0,0 +1,60 @@ +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.apiPayload.exception.PageNumberException; +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 +public class GeneralExceptionAdvice { + + // 애플리케이션에서 발생하는 커스텀 예외를 처리 + @ExceptionHandler(GeneralException.class) + public ResponseEntity> handleException(GeneralException ex) { + return ResponseEntity.status(ex.getCode().getStatus()) + .body(ApiResponse.onFailure(ex.getCode(),null)); + } + + //그 외의 정의되지 않은 모든 예외 처리 + @ExceptionHandler(Exception.class) + public ResponseEntity> handleException(Exception ex) { + BaseErrorCode code = GeneralErrorCode.INTERNAL_SERVER_ERROR; + return ResponseEntity.status(code.getStatus()) + .body(ApiResponse.onFailure(code, ex.getMessage())); + } + + // 컨트롤러 메서드에서 @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(PageNumberException.class) + public ResponseEntity> handlePageNumberException(PageNumberException ex) { + GeneralErrorCode code = GeneralErrorCode.INVALID_REQUEST; + return ResponseEntity.status(code.getStatus()) + .body(ApiResponse.onFailure(code, ex.getMessage())); + } + +} diff --git a/src/main/java/com/example/umc9th/global/config/SecurityConfigJwt.java b/src/main/java/com/example/umc9th/global/config/SecurityConfigJwt.java new file mode 100644 index 0000000..7d626aa --- /dev/null +++ b/src/main/java/com/example/umc9th/global/config/SecurityConfigJwt.java @@ -0,0 +1,76 @@ +package com.example.umc9th.global.config; + +import com.example.umc9th.global.jwt.JwtAuthFilter; +import com.example.umc9th.global.jwt.JwtUtil; +import com.example.umc9th.global.security.AuthenticationEntryPointImpl; +import com.example.umc9th.global.security.CustomUserDetailsService; +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 SecurityConfigJwt { + + private final JwtUtil jwtUtil; + private final CustomUserDetailsService customUserDetailsService; + + private final String[] allowUris = { + "/login", + "/sign-up", + "/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(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/global/config/SecurityConfigSession.java b/src/main/java/com/example/umc9th/global/config/SecurityConfigSession.java new file mode 100644 index 0000000..7c920d6 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/config/SecurityConfigSession.java @@ -0,0 +1,49 @@ +package com.example.umc9th.global.config; + +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.SecurityFilterChain; + +@EnableWebSecurity +//@Configuration +public class SecurityConfigSession { + + private final String[] allowUris = { + "/sign-up", + "/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(form -> form + .defaultSuccessUrl("/swagger-ui/index.html", true) + .permitAll() + ) + .csrf(AbstractHttpConfigurer::disable) + .logout(logout -> logout + .logoutUrl("/logout") + .logoutSuccessUrl("/login?logout") + .permitAll() + ); + + return http.build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/global/config/SwaggerConfig.java b/src/main/java/com/example/umc9th/global/config/SwaggerConfig.java new file mode 100644 index 0000000..09f24a9 --- /dev/null +++ b/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.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.servers.Server; +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; + +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/src/main/java/com/example/umc9th/global/dto/PagedResponse.java b/src/main/java/com/example/umc9th/global/dto/PagedResponse.java new file mode 100644 index 0000000..3412bb9 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/dto/PagedResponse.java @@ -0,0 +1,16 @@ +package com.example.umc9th.global.dto; + +import lombok.Builder; +import lombok.Getter; + +import java.util.List; + +@Getter +@Builder +public class PagedResponse { + private List content; + private int page; + private int size; + private long totalElements; + private int totalPages; +} diff --git a/src/main/java/com/example/umc9th/global/entity/BaseEntity.java b/src/main/java/com/example/umc9th/global/entity/BaseEntity.java new file mode 100644 index 0000000..a5feafa --- /dev/null +++ b/src/main/java/com/example/umc9th/global/entity/BaseEntity.java @@ -0,0 +1,28 @@ +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", nullable = false) + private LocalDateTime updatedAt; + + @Column(name = "deleted_at") + private LocalDateTime deletedAt; +} diff --git a/src/main/java/com/example/umc9th/global/jwt/JwtAuthFilter.java b/src/main/java/com/example/umc9th/global/jwt/JwtAuthFilter.java new file mode 100644 index 0000000..495e1a1 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/jwt/JwtAuthFilter.java @@ -0,0 +1,58 @@ +package com.example.umc9th.global.jwt; + +import com.example.umc9th.global.security.CustomUserDetailsService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.lang.NonNull; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.context.SecurityContextHolder; +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); + + + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/global/jwt/JwtUtil.java b/src/main/java/com/example/umc9th/global/jwt/JwtUtil.java new file mode 100644 index 0000000..f5e6b1b --- /dev/null +++ b/src/main/java/com/example/umc9th/global/jwt/JwtUtil.java @@ -0,0 +1,93 @@ +package com.example.umc9th.global.jwt; + +import com.example.umc9th.global.security.CustomUserDetails; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.io.Decoders; +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.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; + + public JwtUtil( + @Value("${jwt.token.secretKey}") String secret, + @Value("${jwt.token.expiration.access}") Long accessExpiration + ) { + this.secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)); + this.accessExpiration = Duration.ofMillis(accessExpiration); + } + + // AccessToken 생성 + public String createAccessToken(CustomUserDetails user) { + return createToken(user, accessExpiration); + } + + /** 토큰에서 이메일 가져오기 + * + * @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/src/main/java/com/example/umc9th/global/security/AuthenticationEntryPointImpl.java b/src/main/java/com/example/umc9th/global/security/AuthenticationEntryPointImpl.java new file mode 100644 index 0000000..a58922e --- /dev/null +++ b/src/main/java/com/example/umc9th/global/security/AuthenticationEntryPointImpl.java @@ -0,0 +1,33 @@ +package com.example.umc9th.global.security; + +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/src/main/java/com/example/umc9th/global/security/CustomUserDetails.java b/src/main/java/com/example/umc9th/global/security/CustomUserDetails.java new file mode 100644 index 0000000..fd1a4bb --- /dev/null +++ b/src/main/java/com/example/umc9th/global/security/CustomUserDetails.java @@ -0,0 +1,30 @@ +package com.example.umc9th.global.security; + +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/src/main/java/com/example/umc9th/global/security/CustomUserDetailsService.java b/src/main/java/com/example/umc9th/global/security/CustomUserDetailsService.java new file mode 100644 index 0000000..fe3e123 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/security/CustomUserDetailsService.java @@ -0,0 +1,30 @@ +package com.example.umc9th.global.security; + +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.findByEmailAndDeletedAtIsNull(username) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + // CustomUserDetails 반환 + return new CustomUserDetails(member); + } +} + diff --git a/src/main/java/com/example/umc9th/global/validator/FoodExistValidator.java b/src/main/java/com/example/umc9th/global/validator/FoodExistValidator.java new file mode 100644 index 0000000..b476509 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/validator/FoodExistValidator.java @@ -0,0 +1,32 @@ +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(foodRepository::existsById); + + if (!isValid) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(FoodErrorCode.NOT_FOUND.getMessage()).addConstraintViolation(); + } + + return isValid; + + } +} diff --git a/src/main/java/com/example/umc9th/global/validator/ValidPageValidator.java b/src/main/java/com/example/umc9th/global/validator/ValidPageValidator.java new file mode 100644 index 0000000..9b29554 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/validator/ValidPageValidator.java @@ -0,0 +1,25 @@ +package com.example.umc9th.global.validator; + +import com.example.umc9th.global.annotation.ValidPage; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import org.springframework.stereotype.Component; + +@Component +public class ValidPageValidator implements ConstraintValidator { + + @Override + public boolean isValid(Integer value, ConstraintValidatorContext context) { + boolean isValid = value != null && value >= 1; + + if (!isValid) { + // 디폴트 메시지 비활성화 + context.disableDefaultConstraintViolation(); + // 새로운 메시지로 덮어쓰기 + context.buildConstraintViolationWithTemplate("페이지 번호는 1 이상이어야 합니다.") + .addConstraintViolation(); + } + + return isValid; + } +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..e70228c --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,25 @@ +spring: + application: + name: "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 쿼리를 보기 좋게 포맷팅 + +jwt: + token: + secretKey: ZGh3YWlkc2F2ZXdhZXZ3b2EgMTM5ZXUgMDMxdWMyIHEyMiBAIDAgKTJFVio= + expiration: + access: 14400000 diff --git a/src/test/java/com/example/umc9th/Umc9thApplicationTests.java b/src/test/java/com/example/umc9th/Umc9thApplicationTests.java new file mode 100644 index 0000000..bbdf1bd --- /dev/null +++ b/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() { + } + +}