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/README.md b/README.md index a2f07e0..de1f0c7 100644 --- a/README.md +++ b/README.md @@ -1,74 +1,146 @@ -# :leaves: Spring_Boot D - -DGU-UMC 9기 Spring Boot 스터디 D조 - -## 💻 Member - -| 애나 | 루크 | 미로 | 누리 | -| :-----------------------------------: | :-----------------------------------: | :-----------------------------------: | :-----------------------------------: | -| [김민선](https://github.com/sunnyanna0) | [김도훈](https://github.com/DOHOON0127) | [이시은](https://github.com/miro-oss) | [정준영](https://github.com/cokanuri) | - -## 📁 디렉토리 구조 - -- src 디렉토리를 실제 작업을 진행하는 Spring Boot의 src와 일치시켜 주세요. -- 미션 및 실습, 주차를 정확히 구분하기 위해 아래의 commit 규칙을 ‼️반드시‼️ 준수하여 commit 후 push 해 주세요. - -```bash -├─.github -│ └─PULL_REQUEST_TEMPLATE -│ └─ISSUE_TEMPLATE -├─README.md -└─src - ├─main - │ - └─test - │ - └─... - -``` - -## 🎨 commit 규칙 - -- 해당 commit이 미션에 관한 것일 경우: "mission/#해당 주차" - -``` -Ex) 1주차 미션 수행 후 -mission/#01 -``` - -- 해당 commit이 실습에 관한 것일 경우: "practice/#해당 주차" - -``` -Ex) 2주차 실습 수행 후 -practice/#02 -``` - -- 해당 주차에 미션이나 실습이 없는 경우, 있는 주차에만 수행하시면 됩니다. - -## 🌳 branch 규칙 - -```bash -├─main - ├─angela/main - │ └─angela/#1 -``` - -1. `닉네임/main 브랜치`가 기본 브랜치로 pr 보낼 때 root 브랜치(main 브랜치)가 아닌 닉네임/main 브랜치로 올립니다. -2. 매주 워크북, 실습, 그리고 미션은 각자의 닉네임/main 브랜치를 base 브랜치로 삼아 `닉네임/이슈번호 브랜치`를 생성하여 관련 파일을 업로드합니다. -3. 모든 팀원들의 approve를 받으면, pr을 머지하고 해당 pr을 생성한 브랜치(닉네임/이슈번호 브랜치)는 삭제합니다. approve와 merge는 스터디 진행 중에 이루어집니다. - -## 🔖 커밋 컨벤션 - -| Message | 설명 | -| :------: | :-------------------- | -| mission | 미션 수행 | -| practice | 실습 수행 | -| keyword | 키워드 정리 | -| workbook | 워크북 정리 | -| fix | 버그 수정 | -| docs | 문서 수정 | -| comment | 주석 추가 및 변경 | -| test | 테스트 코드 추가 | -| rename | 파일 혹은 폴더명 수정 | -| remove | 파일 혹은 폴더 삭제 | -| chore | 기타 변경사항 | + 속성별 제약조건 정리 + +## member + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| member_id | BIGINT(20) | PK, NOT NULL | 회원 고유 ID | +| name | VARCHAR(50) | NOT NULL | 회원 이름 | +| nickname | VARCHAR(50) | NOT NULL | 닉네임 | +| gender | VARCHAR(10) | NOT NULL | 성별 | +| birth | DATE | NOT NULL | 생년월일 | +| address | VARCHAR(255) | NOT NULL | 주소 | +| status | VARCHAR(15) | NOT NULL | 회원 상태 (정상/탈퇴 등) | +| withdrawal_date | DATETIME | NULL | 탈퇴일 | +| email | VARCHAR(255) | NULL | 이메일 | +| phone | VARCHAR(20) | NULL | 전화번호 | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | +| point | INT(20) | NOT NULL | 보유 포인트 | + +--- + +## food + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| category_id | BIGINT(20) | PK, NOT NULL | 음식 카테고리 ID | +| category_name | VARCHAR(50) | NOT NULL | 음식 카테고리명 | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## member_food + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| id | BIGINT(20) | PK, NOT NULL | 고유 ID | +| member_id | BIGINT(20) | FK → member.member_id | 회원 ID | +| category_id | BIGINT(20) | FK → food.category_id | 음식 카테고리 ID | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## mission + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| mission_id | BIGINT(20) | PK, NOT NULL | 미션 고유 ID | +| store_id | BIGINT(20) | FK → store.store_id | 가게 ID | +| mission_condition | VARCHAR(50) | NOT NULL | 미션 조건 | +| mission_deadline | DATE | NOT NULL | 미션 기한 | +| point | INT(20) | NOT NULL | 포인트 | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## member_mission + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| id | BIGINT(20) | PK, NOT NULL | 고유 ID | +| member_id | BIGINT(20) | FK → member.member_id | 회원 ID | +| mission_id | BIGINT(20) | FK → mission.mission_id | 미션 ID | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## store + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| store_id | BIGINT(20) | PK, NOT NULL | 가게 ID | +| region_id | BIGINT(20) | FK → region.region_id | 지역 ID | +| name | VARCHAR(50) | NOT NULL | 가게 이름 | +| address | VARCHAR(255) | NOT NULL | 가게 주소 | +| rating | DECIMAL(2,1) | NOT NULL | 평점 | +| status | VARCHAR(50) | NOT NULL | 영업 상태 | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## region + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| region_id | BIGINT(20) | PK, NOT NULL | 지역 고유 ID | +| name | VARCHAR(50) | NOT NULL | 지역명 | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## review + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| review_id | BIGINT(20) | PK, NOT NULL | 리뷰 고유 ID | +| store_id | BIGINT(20) | FK → store.store_id | 가게 ID | +| member_id | BIGINT(20) | FK → member.member_id | 작성자 ID | +| content | VARCHAR(255) | NOT NULL | 리뷰 내용 | +| rating | DECIMAL(2,1) | NOT NULL | 평점 | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## review_reply + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| reply_id | BIGINT(20) | PK, NOT NULL | 댓글 ID | +| review_id | BIGINT(20) | FK → review.review_id | 리뷰 ID | +| content | VARCHAR(255) | NOT NULL | 댓글 내용 | +| created_at | DATETIME(6) | NOT NULL | 생성일 | +| updated_at | DATETIME(6) | NOT NULL | 수정일 | + +--- + +## review_photo + +| 컬럼명 | 데이터 타입 | 제약조건 | 설명 | +|--------|--------------|-----------|------| +| photo_id | BIGINT(20) | PK, NOT NULL | 사진 ID | +| review_id | BIGINT(20) | FK → review.review_id | 리뷰 ID | +| photo_url | VARCHAR(255) | NULL | 사진 URL | + +--- + +# 연관관계 매핑 + +| 관계 | 매핑 방향 | 관계 유형 +|------|------------|------------| +| Member – Review | 양방향 | 1:N | +| Member – MemberFood | 양방향 | 1:N | +| Member – MemberMission | 단방향 | 1:N | +| Mission – MemberMission | 양방향 | 1:N | +| Mission – Store | 양방향 | N:1 | +| Store – Region | 양방향 | N:1 | +| Review – ReviewReply | 양방향 | 1:1 | +| Review – ReviewPhoto | 양방향 | 1:N | +| Food – MemberFood | 단방향 | 1:N | diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..032fd01 --- /dev/null +++ b/build.gradle @@ -0,0 +1,78 @@ +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(21) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'com.h2database:h2' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + // QueryDSL - 공식 버전 사용 + implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta' + annotationProcessor 'com.querydsl:querydsl-apt:5.0.0:jakarta' + annotationProcessor 'jakarta.annotation:jakarta.annotation-api' + annotationProcessor 'jakarta.persistence:jakarta.persistence-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 설정 +def generated = layout.buildDirectory.dir('generated/querydsl').get().asFile + +sourceSets { + main.java.srcDirs += [generated] +} + +tasks.withType(JavaCompile) { + options.getGeneratedSourceOutputDirectory().set(file(generated)) +} + +clean { + delete file(generated) +} \ No newline at end of file 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..579dda4 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/controller/MemberController.java @@ -0,0 +1,61 @@ +package com.example.umc9th.domain.member.controller; + +import com.example.umc9th.domain.member.dto.MemberInfoResponseDTO; +import com.example.umc9th.domain.member.dto.req.MemberReqDTO; +import com.example.umc9th.domain.member.dto.res.MemberResDTO; +import com.example.umc9th.domain.member.exception.code.MemberSuccessCode; +import com.example.umc9th.domain.member.service.MemberCommandService; +import com.example.umc9th.domain.member.service.MemberQueryService; +import com.example.umc9th.domain.member.service.MemberService; +import com.example.umc9th.domain.review.dto.ReviewResponseDTO; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/members") +public class MemberController { + + private final MemberService memberService; + 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 com.example.umc9th.global.auth.dto.MemberReqDTO.LoginDTO dto + ){ + return ApiResponse.onSuccess(MemberSuccessCode.FOUND, memberQueryService.login(dto)); + } + + + @GetMapping("{id}/mypage") + public ApiResponse getMyInfo(@PathVariable Long id) { + MemberInfoResponseDTO response = memberService.getMemberInfo(id); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } + + +// @GetMapping("{id}/reviews") +// public ApiResponse> getMyReviews() { +// List response = memberService.getMyReviews(id); +// +// return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); +// } +} \ No newline at end of file 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..4d65a6a --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/converter/MemberConverter.java @@ -0,0 +1,41 @@ +package com.example.umc9th.domain.member.converter; + +import com.example.umc9th.domain.member.dto.req.MemberReqDTO; +import com.example.umc9th.domain.member.dto.res.MemberResDTO; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.global.auth.enums.Role; + +public class MemberConverter { + + public static MemberResDTO.JoinDTO toJoinDTO( + Member member + ) { + return MemberResDTO.JoinDTO.builder() + .memberId(member.getId()) + .createAt(member.getCreatedAt()) + .build(); + } + + public static Member toMember( + MemberReqDTO.JoinDTO dto, + String password, + Role role + ) { + return Member.builder() + .name(dto.name()) + .email(dto.email()) + .password(password) + .role(role) + .birth(dto.birth()) + .address(dto.address()) + .gender(dto.gender()) + .build(); + } + + public static com.example.umc9th.global.auth.dto.MemberResDTO.LoginDTO toLoginDTO(Member member, String accessToken) { + return com.example.umc9th.global.auth.dto.MemberResDTO.LoginDTO.builder() + .memberId(member.getId()) + .accessToken(accessToken) + .build(); + } +} diff --git a/src/main/java/com/example/umc9th/domain/member/dto/MemberInfoResponseDTO.java b/src/main/java/com/example/umc9th/domain/member/dto/MemberInfoResponseDTO.java new file mode 100644 index 0000000..91cef08 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/dto/MemberInfoResponseDTO.java @@ -0,0 +1,18 @@ +package com.example.umc9th.domain.member.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class MemberInfoResponseDTO { + + private String nickname; + private String phoneNumber; + private Integer point; + private String email; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/member/dto/req/MemberReqDTO.java b/src/main/java/com/example/umc9th/domain/member/dto/req/MemberReqDTO.java new file mode 100644 index 0000000..71f85c8 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/dto/req/MemberReqDTO.java @@ -0,0 +1,33 @@ +package com.example.umc9th.domain.member.dto.req; + +import com.example.umc9th.domain.member.enums.Address; +import com.example.umc9th.domain.member.enums.Gender; +import com.example.umc9th.global.annotation.ExistFoods; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.time.LocalDate; +import java.util.List; + +public class MemberReqDTO { + + public record JoinDTO( + @NotBlank + String name, + @Email + String email, + @NotBlank + String password, + @NotNull + Gender gender, + @NotNull + LocalDate birth, + @NotNull + Address address, + @NotNull + String specAddress, + @ExistFoods + List preferCategory + ){} +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/member/dto/res/MemberResDTO.java b/src/main/java/com/example/umc9th/domain/member/dto/res/MemberResDTO.java new file mode 100644 index 0000000..6de331d --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/dto/res/MemberResDTO.java @@ -0,0 +1,14 @@ +package com.example.umc9th.domain.member.dto.res; + +import lombok.Builder; + +import java.time.LocalDateTime; + +public class MemberResDTO { + + @Builder + public record JoinDTO( + Long memberId, + LocalDateTime createAt + ){} +} 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..0fc7d74 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/Food.java @@ -0,0 +1,24 @@ +package com.example.umc9th.domain.member.entity; + +import com.example.umc9th.domain.member.enums.FoodName; +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 = "food") +public class Food extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + @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..ece4794 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/Member.java @@ -0,0 +1,82 @@ +package com.example.umc9th.domain.member.entity; + + +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +import com.example.umc9th.domain.member.enums.Address; +import com.example.umc9th.domain.member.enums.Gender; +import com.example.umc9th.domain.member.enums.MemberStatus; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.global.auth.enums.Role; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Table(name = "member") +@EntityListeners(AuditingEntityListener.class) +public class Member extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", length = 5, nullable = false) + private String name; + + @Column(name = "gender", nullable = false) + @Enumerated(EnumType.STRING) + @Builder.Default + private Gender gender = Gender.NONE; + + @Column(name = "birth", nullable = false) + private LocalDate birth; + + @Column(name = "address", nullable = false) + @Enumerated(EnumType.STRING) + private Address address; + + @Column(name = "detail_address") + private String detailAddress; + + @Column(name = "status" , nullable = true) + @Enumerated(EnumType.STRING) + private MemberStatus status; + + @Column(name = "inactive_date") + private LocalDate inactiveDate; + + @Column(name = "email",nullable = false,unique = true) + private String email; + + @Column(nullable = false) + private String password; + + @Enumerated(EnumType.STRING) + private Role role; + + @Column(name = "phone_number") + private String phoneNumber; + + @Column(name = "point") + @Builder.Default + private Integer point = 0 ; + + @OneToMany(mappedBy = "member", cascade = CascadeType.REMOVE) + @Builder.Default + private List memberFoodList = new ArrayList<>(); + + @OneToMany(mappedBy = "member") + private List reviewList = new ArrayList<>(); +} 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..21eccd9 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/entity/mapping/MemberFood.java @@ -0,0 +1,29 @@ +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 jakarta.persistence.*; +import lombok.*; +import org.springframework.context.annotation.Lazy; + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "member_food") +public class MemberFood { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "food_id") + private Food food; + +} 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..fe6d9fb --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/Address.java @@ -0,0 +1,6 @@ +package com.example.umc9th.domain.member.enums; + +public enum Address { + 안암, + 신촌 +} 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..e269124 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/FoodName.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.member.enums; + +public enum FoodName { + KOREAN,JAPANESE,CHINESE,WESTERN,CHICKEN,NONE +} 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..2d54bbc --- /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/MemberStatus.java b/src/main/java/com/example/umc9th/domain/member/enums/MemberStatus.java new file mode 100644 index 0000000..3af9ec1 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/enums/MemberStatus.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.member.enums; + +public enum MemberStatus { + ACTIVE,INACTIVE +} 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..71f7432 --- /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..34a9f18 --- /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..76f5c6f --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/exception/code/MemberErrorCode.java @@ -0,0 +1,22 @@ +package com.example.umc9th.domain.member.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum MemberErrorCode implements BaseErrorCode { + + NOT_FOUND(HttpStatus.NOT_FOUND, + "MEMBER404_1", + "해당 사용자를 찾지 못했습니다."), + INVALID(HttpStatus.BAD_REQUEST, + "MEMBER404_2" , + "비밀번호가 일치하지 않습니다." ); + + 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..5b1e0e0 --- /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; +} \ No newline at end of file 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..4107892 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/repository/FoodRepository.java @@ -0,0 +1,7 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.Food; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FoodRepository extends JpaRepository { +} diff --git a/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..10e8d97 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/repository/MemberFoodRepository.java @@ -0,0 +1,8 @@ +package com.example.umc9th.domain.member.repository; + +import com.example.umc9th.domain.member.entity.Food; +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..ea767c8 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/repository/MemberRepository.java @@ -0,0 +1,11 @@ +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 findByEmail(String email); +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/MemberCommandService.java b/src/main/java/com/example/umc9th/domain/member/service/MemberCommandService.java new file mode 100644 index 0000000..19cc6c7 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/MemberCommandService.java @@ -0,0 +1,9 @@ +package com.example.umc9th.domain.member.service; + +import com.example.umc9th.domain.member.dto.req.MemberReqDTO; +import com.example.umc9th.domain.member.dto.res.MemberResDTO; + +public interface MemberCommandService { + + public MemberResDTO.JoinDTO signUp(MemberReqDTO.JoinDTO dto); +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/MemberCommandServiceImpl.java b/src/main/java/com/example/umc9th/domain/member/service/MemberCommandServiceImpl.java new file mode 100644 index 0000000..d0c83db --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/MemberCommandServiceImpl.java @@ -0,0 +1,75 @@ +package com.example.umc9th.domain.member.service; + +import com.example.umc9th.domain.member.converter.MemberConverter; +import com.example.umc9th.domain.member.dto.req.MemberReqDTO; +import com.example.umc9th.domain.member.dto.res.MemberResDTO; +import com.example.umc9th.domain.member.entity.Food; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.entity.mapping.MemberFood; +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 com.example.umc9th.global.auth.enums.Role; +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; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class MemberCommandServiceImpl implements MemberCommandService { + + private final MemberRepository memberRepository; + private final FoodRepository foodRepository; + private final MemberFoodRepository memberFoodRepository; + + private final PasswordEncoder passwordEncoder; + + //회원가입 + @Override + @Transactional + public MemberResDTO.JoinDTO signUp( + MemberReqDTO.JoinDTO dto + ) { + + String salt = passwordEncoder.encode(dto.password()); + + Member member = MemberConverter.toMember(dto,salt, Role.ROLE_USER); + memberRepository.save(member); + +// if (dto.preferCategory().size() > 1) { +// List memberFoodList = new ArrayList<>(); +// +// for (Long id : dto.preferCategory()) { +// Food food = foodRepository.findById(id) +// .orElseThrow(() -> new FoodException(FoodErrorCode.NOT_FOUND)); +// +// MemberFood memberFood = MemberFood.builder() +// .member(member) +// .food(food) +// .build(); +// +// memberFoodList.add(memberFood); +// } +// memberFoodRepository.saveAll(memberFoodList); +// } + + if (dto.preferCategory().size() > 1) { + List memberFoodList = dto.preferCategory().stream() + .map(id -> MemberFood.builder() + .member(member) + .food(foodRepository.findById(id) + .orElseThrow(()->new FoodException(FoodErrorCode.NOT_FOUND))) + .build() + ).collect(Collectors.toList()); + memberFoodRepository.saveAll(memberFoodList); + } + return MemberConverter.toJoinDTO(member); + } +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/MemberQueryService.java b/src/main/java/com/example/umc9th/domain/member/service/MemberQueryService.java new file mode 100644 index 0000000..94c9e1b --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/MemberQueryService.java @@ -0,0 +1,12 @@ +package com.example.umc9th.domain.member.service; + +import com.example.umc9th.global.auth.dto.MemberReqDTO; +import com.example.umc9th.global.auth.dto.MemberResDTO; +import jakarta.validation.Valid; + +public interface MemberQueryService { + + + MemberResDTO.LoginDTO login(MemberReqDTO.LoginDTO dto); + +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/MemberQueryServiceImpl.java b/src/main/java/com/example/umc9th/domain/member/service/MemberQueryServiceImpl.java new file mode 100644 index 0000000..2ef943a --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/MemberQueryServiceImpl.java @@ -0,0 +1,41 @@ +package com.example.umc9th.domain.member.service; + +import com.example.umc9th.domain.member.converter.MemberConverter; +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.auth.JwtUtil; +import com.example.umc9th.global.auth.dto.MemberReqDTO; +import com.example.umc9th.global.auth.dto.MemberResDTO; +import com.example.umc9th.global.auth.entity.CustomUserDetails; +import jakarta.validation.Valid; +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.@Valid LoginDTO dto) + { + Member member = memberRepository.findByEmail(dto.email()) + .orElseThrow(() -> new MemberException(MemberErrorCode.NOT_FOUND)); + + if (!encoder.matches(dto.password(), member.getPassword())) { + throw new MemberException(MemberErrorCode.INVALID); + } + + CustomUserDetails userDetails = new CustomUserDetails(member); + + String accessToken = jwtUtil.createAccessToken(userDetails); + + return MemberConverter.toLoginDTO(member, accessToken); + } +} diff --git a/src/main/java/com/example/umc9th/domain/member/service/MemberService.java b/src/main/java/com/example/umc9th/domain/member/service/MemberService.java new file mode 100644 index 0000000..45fc616 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/member/service/MemberService.java @@ -0,0 +1,31 @@ +package com.example.umc9th.domain.member.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.example.umc9th.domain.member.dto.MemberInfoResponseDTO; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.repository.MemberRepository; + +import java.util.NoSuchElementException; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class MemberService { + + private final MemberRepository memberRepository; + + public MemberInfoResponseDTO getMemberInfo(Long memberId) { + + Member member = memberRepository.findById(memberId) + .orElseThrow(() -> new NoSuchElementException( memberId + "를 찾을 수 없습니다")); + + return MemberInfoResponseDTO.builder() + .nickname(member.getName()) + .phoneNumber(member.getPhoneNumber()) + .point(member.getPoint()) + .email(member.getEmail()) + .build(); + } +} \ 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..ac2d746 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/controller/MissionController.java @@ -0,0 +1,69 @@ +package com.example.umc9th.domain.mission.controller; + +import com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO; +import com.example.umc9th.domain.mission.dto.HomeMissionResponseDTO; +import com.example.umc9th.domain.mission.dto.MissionResponseDTO; +import com.example.umc9th.domain.mission.exception.code.MissionSuccessCode; +import com.example.umc9th.domain.mission.service.MissionCommandService; +import com.example.umc9th.domain.mission.service.MissionService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/missions") +public class MissionController { + + private final MissionService missionService; + private final MissionCommandService missionCommandService; + + @PostMapping( "/{missionId}/members/{memberId}/challenge") + public ApiResponse challengeMission( + @PathVariable Long memberId, + @PathVariable Long missionId + ) { + + return ApiResponse.onSuccess(MissionSuccessCode.MISSION_CREATED, missionCommandService.challengeMission(memberId, missionId)); + } + + @GetMapping("/home") + public ApiResponse getHomeMissions( + @PathVariable Long memberId, + @PathVariable Long regionId, + @PageableDefault(size = 5) Pageable pageable) { + + HomeMissionResponseDTO response = + missionService.getHomeMissions(memberId, regionId , pageable); + + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } + + + @GetMapping("/ongoing") + public ApiResponse> getOngoingMissions( + @PathVariable Long memberId, + @PageableDefault(size = 10) Pageable pageable) { + + Page response = + missionService.getOngoingMissions(memberId, pageable); + + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } + + + @GetMapping("/completed") + public ApiResponse> getCompletedMissions( + @PathVariable Long memberId, + @PageableDefault(size = 10) Pageable pageable) { + + Page response = + missionService.getCompletedMissions(memberId, pageable); + + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/dto/ChallengeMissionResponseDTO.java b/src/main/java/com/example/umc9th/domain/mission/dto/ChallengeMissionResponseDTO.java new file mode 100644 index 0000000..186a32d --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/dto/ChallengeMissionResponseDTO.java @@ -0,0 +1,21 @@ +package com.example.umc9th.domain.mission.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class ChallengeMissionResponseDTO { + private Long missionId; + private String storeName; + private LocalDate deadline; // LocalDateTime → LocalDate + private String condition; + private Integer point; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/dto/HomeMissionResponseDTO.java b/src/main/java/com/example/umc9th/domain/mission/dto/HomeMissionResponseDTO.java new file mode 100644 index 0000000..42f053c --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/dto/HomeMissionResponseDTO.java @@ -0,0 +1,21 @@ +package com.example.umc9th.domain.mission.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.domain.Page; + + +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class HomeMissionResponseDTO { + + private Long completedCount; + private Long totalCount; + + // 미션 목록 + private Page missionList; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/dto/MissionResponseDTO.java b/src/main/java/com/example/umc9th/domain/mission/dto/MissionResponseDTO.java new file mode 100644 index 0000000..5b20158 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/dto/MissionResponseDTO.java @@ -0,0 +1,21 @@ +package com.example.umc9th.domain.mission.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class MissionResponseDTO { + + private Long missionId; + private String storeName; + private String conditional; + private Integer point; + private String missionStatus; +} \ 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..1c897a1 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/entity/Mission.java @@ -0,0 +1,41 @@ +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.LocalDate; +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; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + @Column(name = "conditional", nullable = false) + private String conditional; + + @Column(name = "deadline", nullable = false) + private LocalDate deadline; + + @Column(name = "point_reward", nullable = false) + private int pointReward; + + @OneToMany(mappedBy = "mission") + private List memberMissionList = 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..49c00b8 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/entity/mapping/MemberMission.java @@ -0,0 +1,34 @@ +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.MemberMissionStatus; +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") +public class MemberMission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "mission_id") + private Mission mission; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 20) + private MemberMissionStatus status; + +} diff --git a/src/main/java/com/example/umc9th/domain/mission/enums/MemberMissionStatus.java b/src/main/java/com/example/umc9th/domain/mission/enums/MemberMissionStatus.java new file mode 100644 index 0000000..ed07a6a --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/enums/MemberMissionStatus.java @@ -0,0 +1,7 @@ +package com.example.umc9th.domain.mission.enums; + + +public enum MemberMissionStatus { + ONGOING, + COMPLETED, +} 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..1b05a66 --- /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); + } +} 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..4ed5809 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionErrorCode.java @@ -0,0 +1,19 @@ +package com.example.umc9th.domain.mission.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum MissionErrorCode implements BaseErrorCode { + NOT_FOUND(HttpStatus.NOT_FOUND, + "MISSION404_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/MissionSuccessCode.java b/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java new file mode 100644 index 0000000..e52acef --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/exception/code/MissionSuccessCode.java @@ -0,0 +1,21 @@ +package com.example.umc9th.domain.mission.exception.code; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +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_FETCHED(HttpStatus.OK, "MISSION200_1", "미션 목록 조회가 완료되었습니다."), + HOME_MISSIONS_FETCHED(HttpStatus.OK, "MISSION200_2", "홈 화면 미션 조회가 완료되었습니다."), + MISSION_CREATED(HttpStatus.CREATED, "MISSION201_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/mission/repository/MemberMissionRepository.java b/src/main/java/com/example/umc9th/domain/mission/repository/MemberMissionRepository.java new file mode 100644 index 0000000..a6270fb --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/repository/MemberMissionRepository.java @@ -0,0 +1,43 @@ +package com.example.umc9th.domain.mission.repository; + +import com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO; +import com.example.umc9th.domain.mission.enums.MemberMissionStatus; +import com.example.umc9th.domain.mission.dto.MissionResponseDTO; +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.time.LocalDateTime; + +public interface MemberMissionRepository extends JpaRepository { + + + @Query("SELECT new com.example.umc9th.domain.mission.dto.MissionResponseDTO(" + + "ms.id, s.name, ms.conditional, ms.pointReward, CAST(m.status AS string)) " + + "FROM MemberMission m " + + "JOIN m.mission ms " + + "JOIN ms.store s " + + "WHERE m.member.id = :memberId AND m.status = :status " + + "ORDER BY m.createdAt DESC") + Page findMemberMissionsByStatus( + @Param("memberId") Long memberId, + @Param("status") String status, + Pageable pageable + ); + + @Query("SELECT COUNT(m) " + + "FROM MemberMission m JOIN m.mission ms JOIN ms.store s " + + "WHERE m.member.id = :memberId " + + "AND m.status = 'COMPLETED' " + + "AND s.region.id = :regionId") + Long countCompletedMissionsByMemberAndRegion( + @Param("memberId") Long memberId, + @Param("regionId") Long regionId + ); + + +} \ No newline at end of file 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..2f76824 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/repository/MissionRepository.java @@ -0,0 +1,27 @@ +package com.example.umc9th.domain.mission.repository; + +import com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO; +import com.example.umc9th.domain.mission.entity.Mission; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.time.LocalDate; + +public interface MissionRepository extends JpaRepository { + + + @Query("SELECT new com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO(" + + "ms.id, s.name, ms.deadline, ms.conditional, ms.pointReward) " + + "FROM Mission ms JOIN ms.store s " + + "WHERE s.region.id = :regionId " + + "AND ms.deadline > :now " + + "ORDER BY ms.createdAt DESC") + Page findChallengeableMissionsByRegion( + @Param("regionId") Long regionId, + @Param("now") LocalDate now, + Pageable pageable + ); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/mission/service/MissionCommandService.java b/src/main/java/com/example/umc9th/domain/mission/service/MissionCommandService.java new file mode 100644 index 0000000..43a4c4a --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/MissionCommandService.java @@ -0,0 +1,8 @@ +package com.example.umc9th.domain.mission.service; + +import com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO; + +public interface MissionCommandService { + + ChallengeMissionResponseDTO challengeMission(Long memberId, Long missionId); +} diff --git a/src/main/java/com/example/umc9th/domain/mission/service/MissionCommandServiceImpl.java b/src/main/java/com/example/umc9th/domain/mission/service/MissionCommandServiceImpl.java new file mode 100644 index 0000000..2133b91 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/MissionCommandServiceImpl.java @@ -0,0 +1,53 @@ +package com.example.umc9th.domain.mission.service; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.exception.code.MemberErrorCode; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO; +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.mission.entity.mapping.MemberMission; +import com.example.umc9th.domain.mission.enums.MemberMissionStatus; +import com.example.umc9th.domain.mission.exception.MissionException; +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.util.Optional; + +@Service +@RequiredArgsConstructor +public class MissionCommandServiceImpl implements MissionCommandService { + + private final MemberRepository memberRepository; + private final MissionRepository missionRepository; + private final MemberMissionRepository memberMissionRepository; + + @Override + @Transactional + public ChallengeMissionResponseDTO challengeMission(Long memberId, Long missionId) { + Member member = memberRepository.findById(memberId) + .orElseThrow(() -> new MemberException(MemberErrorCode.NOT_FOUND)); + Mission mission = missionRepository.findById(missionId) + .orElseThrow(() -> new MissionException(MissionErrorCode.NOT_FOUND)); + + MemberMission memberMission = MemberMission.builder() + .member(member) + .mission(mission) + .status(MemberMissionStatus.ONGOING) + .build(); + + memberMissionRepository.save(memberMission); + + return ChallengeMissionResponseDTO.builder() + .missionId(mission.getId()) + .storeName(mission.getStore().getName()) + .deadline(mission.getDeadline()) + .condition(mission.getConditional()) + .point(mission.getPointReward()) + .build(); + } +} diff --git a/src/main/java/com/example/umc9th/domain/mission/service/MissionService.java b/src/main/java/com/example/umc9th/domain/mission/service/MissionService.java new file mode 100644 index 0000000..35a1c9c --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/mission/service/MissionService.java @@ -0,0 +1,62 @@ +package com.example.umc9th.domain.mission.service; + +import com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO; +import com.example.umc9th.domain.mission.dto.HomeMissionResponseDTO; +import com.example.umc9th.domain.mission.enums.MemberMissionStatus; +import com.example.umc9th.domain.mission.dto.MissionResponseDTO; +import com.example.umc9th.domain.mission.repository.MemberMissionRepository; + +import com.example.umc9th.domain.mission.repository.MissionRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class MissionService { + + private final MemberMissionRepository memberMissionRepository; + private final MissionRepository missionRepository; + + public Page getOngoingMissions(Long memberId, Pageable pageable) { + return memberMissionRepository.findMemberMissionsByStatus( + memberId, + MemberMissionStatus.ONGOING.name(), // 진행 중 상태 + pageable + ); + } + + public Page getCompletedMissions(Long memberId, Pageable pageable) { + return memberMissionRepository.findMemberMissionsByStatus( + memberId, + MemberMissionStatus.COMPLETED.name(), // 완료 상태 + pageable + ); + } + + public HomeMissionResponseDTO getHomeMissions(Long memberId, Long regionId, Pageable pageable) { + + // 지역에서 도전 가능한 미션 목록 조회 + Page challengeableMissions = + missionRepository.findChallengeableMissionsByRegion(regionId, LocalDate.now(), pageable); + + // 지역에서 회원이 성공한 미션 개수 조회 + Long completedCount = memberMissionRepository.countCompletedMissionsByMemberAndRegion(memberId, regionId); + + // 총 미션 개수는 해당 지역의 도전 가능한 미션 총 개수 + Long totalCount = challengeableMissions.getTotalElements(); + + // 두 결과를 최종 응답 DTO로 묶어서 반환 + return HomeMissionResponseDTO.builder() + .completedCount(completedCount) + .totalCount(totalCount) + .missionList(challengeableMissions) + .build(); + } + +} \ No newline at end of file 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..6e45558 --- /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.dto.ReviewDetailResponseDTO; +import com.example.umc9th.domain.review.dto.ReviewFilterRequest; +import com.example.umc9th.domain.review.dto.ReviewRequestDTO; +import com.example.umc9th.domain.review.dto.ReviewResponseDTO; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.review.service.ReviewCommandService; +import com.example.umc9th.domain.review.service.ReviewQueryService; // 필터링 조회 +import com.example.umc9th.domain.review.service.ReviewService; // 리뷰 작성 +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/stores/{storeId}/reviews") +public class ReviewController { + + private final ReviewService reviewService; + private final ReviewCommandService reviewCommandService; + private final ReviewQueryService reviewQueryService; + + + + @PostMapping("/members/{memberId}") + public ApiResponse createReview(@PathVariable Long storeId, + @PathVariable Long memberId, + @RequestBody ReviewRequestDTO request) { + + return ApiResponse.onSuccess(GeneralSuccessCode.CREATED, reviewCommandService.createReview(storeId, memberId, request)); + } + + + @GetMapping("/my") + public ApiResponse> getMyFilteredReviews( + @PathVariable Long storeId, + @PathVariable Long memberId, + @RequestParam(required = false) Double rating, // 별점대 필터링 (예: 4.0, 3.0) + @PageableDefault(size = 10) Pageable pageable) { + + ReviewFilterRequest filterRequest = new ReviewFilterRequest(); + + // Request DTO에 필터링 조건 설정 + filterRequest.setStoreId(storeId); // 경로 변수 storeId 사용 + filterRequest.setRating(rating); // 쿼리 파라미터 rating 사용 + + Page response = + reviewQueryService.getMyFilteredReviews(memberId, filterRequest, pageable); + + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/dto/ReviewDetailResponseDTO.java b/src/main/java/com/example/umc9th/domain/review/dto/ReviewDetailResponseDTO.java new file mode 100644 index 0000000..72de417 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/dto/ReviewDetailResponseDTO.java @@ -0,0 +1,31 @@ +package com.example.umc9th.domain.review.dto; + +import com.querydsl.core.annotations.QueryProjection; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Getter +@NoArgsConstructor +public class ReviewDetailResponseDTO { + + private Long reviewId; + private String nickname; + private Double rating; + private String content; + private LocalDateTime createdAt; + private String replyContent; + private LocalDateTime replyCreatedAt; + + @QueryProjection + public ReviewDetailResponseDTO(Long reviewId, String nickname, Double rating, String content, LocalDateTime createdAt, String replyContent, LocalDateTime replyCreatedAt) { + this.reviewId = reviewId; + this.nickname = nickname; + this.rating = rating; + this.content = content; + this.createdAt = createdAt; + this.replyContent = replyContent; + this.replyCreatedAt = replyCreatedAt; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/dto/ReviewFilterRequest.java b/src/main/java/com/example/umc9th/domain/review/dto/ReviewFilterRequest.java new file mode 100644 index 0000000..38553a8 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/dto/ReviewFilterRequest.java @@ -0,0 +1,15 @@ +package com.example.umc9th.domain.review.dto; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +public class ReviewFilterRequest { + + private Long storeId; + + private Double rating; +} diff --git a/src/main/java/com/example/umc9th/domain/review/dto/ReviewRequestDTO.java b/src/main/java/com/example/umc9th/domain/review/dto/ReviewRequestDTO.java new file mode 100644 index 0000000..c7a895c --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/dto/ReviewRequestDTO.java @@ -0,0 +1,15 @@ +package com.example.umc9th.domain.review.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class ReviewRequestDTO { + + private String content; + private Double rating; + +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/dto/ReviewResponseDTO.java b/src/main/java/com/example/umc9th/domain/review/dto/ReviewResponseDTO.java new file mode 100644 index 0000000..54884b2 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/dto/ReviewResponseDTO.java @@ -0,0 +1,19 @@ +package com.example.umc9th.domain.review.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class ReviewResponseDTO { + + private Long reviewId; + private String storeName; + private String content; + private Double rating; + +} \ 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..0cd9934 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/entity/Reply.java @@ -0,0 +1,26 @@ +package com.example.umc9th.domain.review.entity; + +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "reply") +public class Reply extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "review_id") + private Review review; + + @Column(name = "content", nullable = false) + private String content; + +} 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..da311ab --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/entity/Review.java @@ -0,0 +1,46 @@ +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 com.querydsl.core.annotations.QueryType; +import com.querydsl.core.types.PathType; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Table(name = "review") +@Builder +public class Review extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "content", nullable = false) + private String content; + + @Column(name = "rating", nullable = false) + private Double rating; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + @OneToOne(mappedBy = "review") + private Reply reply; + + @OneToMany(mappedBy = "review", cascade = CascadeType.REMOVE) + 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..7e70620 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/entity/ReviewPhoto.java @@ -0,0 +1,26 @@ +package com.example.umc9th.domain.review.entity; + +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + + +@Entity +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +@Table(name = "review_photo") +public class ReviewPhoto extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "review_id") + private Review review; + + @Column(name = "photo_url", nullable = false) + private String photoUrl; +} 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..51738c8 --- /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 { + NOT_FOUND(HttpStatus.NOT_FOUND, + "REVIEW404_1", + "해당 미션을 찾지 못했습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} 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..a91b743 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/exception/code/ReviewSuccessCode.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 ReviewSuccessCode implements BaseErrorCode { + NOT_FOUND(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/ReviewQueryDsl.java b/src/main/java/com/example/umc9th/domain/review/repository/ReviewQueryDsl.java new file mode 100644 index 0000000..2bb133e --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/repository/ReviewQueryDsl.java @@ -0,0 +1,15 @@ +package com.example.umc9th.domain.review.repository; + +import com.example.umc9th.domain.review.dto.ReviewDetailResponseDTO; +import com.example.umc9th.domain.review.dto.ReviewFilterRequest; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +public interface ReviewQueryDsl { + Page findMyReviewsWithFilter( + Long memberId, + ReviewFilterRequest request, + Pageable pageable); +} diff --git a/src/main/java/com/example/umc9th/domain/review/repository/ReviewQueryDslImpl.java b/src/main/java/com/example/umc9th/domain/review/repository/ReviewQueryDslImpl.java new file mode 100644 index 0000000..3349d1b --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/repository/ReviewQueryDslImpl.java @@ -0,0 +1,84 @@ +package com.example.umc9th.domain.review.repository; + +import com.example.umc9th.domain.review.dto.ReviewDetailResponseDTO; +import com.example.umc9th.domain.review.dto.ReviewFilterRequest; +import com.example.umc9th.domain.review.dto.QReviewDetailResponseDTO; +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.jpa.impl.JPAQueryFactory; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +import static com.example.umc9th.domain.review.entity.QReview.review; +import static com.example.umc9th.domain.member.entity.QMember.member; +import static com.example.umc9th.domain.review.entity.QReply.reply; + +@RequiredArgsConstructor +public class ReviewQueryDslImpl implements ReviewQueryDsl { + + private final JPAQueryFactory queryFactory; + + @Override + public Page findMyReviewsWithFilter( + Long memberId, + ReviewFilterRequest request, + Pageable pageable) { + + BooleanBuilder builder = new BooleanBuilder(); + builder.and(review.member.id.eq(memberId)); + + if (request.getStoreId() != null) { + builder.and(storeIdEq(request.getStoreId())); + } + + if (request.getRating() != null) { + builder.and(ratingBetween(request.getRating())); + } + + List content = queryFactory + .select(new QReviewDetailResponseDTO( + review.id, + review.member.name, + review.rating, + review.content, + review.createdAt, + reply.content, + reply.createdAt + )) + .from(review) + .join(review.member, member) + .leftJoin(reply).on(reply.review.eq(review)) + .where(builder) + .orderBy(review.createdAt.desc()) + .offset(pageable.getOffset()) + .limit(pageable.getPageSize()) + .fetch(); + + Long total = queryFactory + .select(review.count()) + .from(review) + .where(builder) + .fetchOne(); + + return new PageImpl<>(content, pageable, total != null ? total : 0L); + } + + private BooleanExpression storeIdEq(Long storeId) { + return storeId != null ? review.store.id.eq(storeId) : null; + } + + private BooleanExpression ratingBetween(Double rating) { + if (rating == null) { + return null; + } + double nextRating = rating + 1.0; + + // rating은 Double이므로 goe, lt 사용 가능 + return review.rating.goe(rating) + .and(review.rating.lt(nextRating)); + } +} \ No newline at end of file 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..498df93 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/repository/ReviewRepository.java @@ -0,0 +1,20 @@ +package com.example.umc9th.domain.review.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import com.example.umc9th.domain.review.dto.ReviewResponseDTO; +import com.example.umc9th.domain.review.entity.Review; +import java.util.List; + +public interface ReviewRepository extends JpaRepository, ReviewQueryDsl { + + + @Query("SELECT new com.example.umc9th.domain.review.dto.ReviewResponseDTO(" + + "r.id, s.name, r.content, r.rating) " + + "FROM Review r JOIN r.store s " + + "WHERE r.member.id = :memberId " + + "ORDER BY r.createdAt DESC") + List findMemberReviews(@Param("memberId") Long memberId); + +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/service/ReviewCommandService.java b/src/main/java/com/example/umc9th/domain/review/service/ReviewCommandService.java new file mode 100644 index 0000000..f484357 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/service/ReviewCommandService.java @@ -0,0 +1,8 @@ +package com.example.umc9th.domain.review.service; + +import com.example.umc9th.domain.review.dto.ReviewRequestDTO; +import com.example.umc9th.domain.review.dto.ReviewResponseDTO; + +public interface ReviewCommandService { + ReviewResponseDTO createReview(Long storeId, Long memberId, ReviewRequestDTO request); +} diff --git a/src/main/java/com/example/umc9th/domain/review/service/ReviewCommandServiceImpl.java b/src/main/java/com/example/umc9th/domain/review/service/ReviewCommandServiceImpl.java new file mode 100644 index 0000000..17b7199 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/service/ReviewCommandServiceImpl.java @@ -0,0 +1,60 @@ +package com.example.umc9th.domain.review.service; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.exception.MemberException; +import com.example.umc9th.domain.member.exception.code.MemberErrorCode; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.mission.exception.MissionException; +import com.example.umc9th.domain.mission.exception.code.MissionErrorCode; +import com.example.umc9th.domain.review.dto.ReviewRequestDTO; +import com.example.umc9th.domain.review.dto.ReviewResponseDTO; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.review.exception.ReviewException; +import com.example.umc9th.domain.review.exception.code.ReviewErrorCode; +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 lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.NoSuchElementException; + +@Service +@RequiredArgsConstructor +public class ReviewCommandServiceImpl implements ReviewCommandService{ + + private final MemberRepository memberRepository; + private final StoreRepository storeRepository; + private final ReviewRepository reviewRepository; + + @Override + @Transactional + public ReviewResponseDTO createReview(Long storeId, Long memberId, ReviewRequestDTO request) { + + Member member = memberRepository.findById(memberId) + .orElseThrow(() -> new MemberException(MemberErrorCode.NOT_FOUND)); + + Store store = storeRepository.findById(storeId) + .orElseThrow(() -> new StoreException(StoreErrorCode.NOT_FOUND)); + + Review newReview = Review.builder() + .member(member) + .store(store) + .content(request.getContent()) + .rating(request.getRating()) + .build(); + + reviewRepository.save(newReview); + + return ReviewResponseDTO.builder() + .reviewId(newReview.getId()) + .storeName(newReview.getStore().getName()) + .content(request.getContent()) + .rating(request.getRating()) + .build(); + + } +} diff --git a/src/main/java/com/example/umc9th/domain/review/service/ReviewQueryService.java b/src/main/java/com/example/umc9th/domain/review/service/ReviewQueryService.java new file mode 100644 index 0000000..5edaa6d --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/service/ReviewQueryService.java @@ -0,0 +1,27 @@ +package com.example.umc9th.domain.review.service; + +import com.example.umc9th.domain.review.dto.ReviewDetailResponseDTO; +import com.example.umc9th.domain.review.dto.ReviewFilterRequest; +import com.example.umc9th.domain.review.repository.ReviewQueryDsl; +import com.example.umc9th.domain.review.repository.ReviewRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class ReviewQueryService { + + private final ReviewRepository reviewRepository; + + public Page getMyFilteredReviews( + Long memberId, + ReviewFilterRequest request, + Pageable pageable) { + + return reviewRepository.findMyReviewsWithFilter(memberId, request, pageable); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/domain/review/service/ReviewService.java b/src/main/java/com/example/umc9th/domain/review/service/ReviewService.java new file mode 100644 index 0000000..59bd275 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/review/service/ReviewService.java @@ -0,0 +1,51 @@ +package com.example.umc9th.domain.review.service; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.review.dto.ReviewRequestDTO; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.store.entity.Store; +import com.example.umc9th.domain.store.repository.StoreRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.example.umc9th.domain.review.dto.ReviewResponseDTO; +import com.example.umc9th.domain.review.repository.ReviewRepository; + +import java.util.List; +import java.util.NoSuchElementException; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class ReviewService { + + private final ReviewRepository reviewRepository; + private final MemberRepository memberRepository; + private final StoreRepository storeRepository; + + public List getMyReviews(Long memberId) { + + return reviewRepository.findMemberReviews(memberId); + } + + public Review createReview(Long storeId, Long memberId, ReviewRequestDTO request) { + + Member member = memberRepository.findById(memberId) + .orElseThrow(() -> new NoSuchElementException(memberId + "를 찾을 수 없습니다.")); + + Store store = storeRepository.findById(storeId) + .orElseThrow(() -> new NoSuchElementException(storeId + "를 찾을 수 없습니다.")); + + Review newReview = Review.builder() + .member(member) + .store(store) + .content(request.getContent()) + .rating(request.getRating()) + .build(); + + reviewRepository.save(newReview); + + return newReview; + } +} diff --git a/src/main/java/com/example/umc9th/domain/store/entity/Region.java b/src/main/java/com/example/umc9th/domain/store/entity/Region.java new file mode 100644 index 0000000..bf4ad4e --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/entity/Region.java @@ -0,0 +1,28 @@ +package com.example.umc9th.domain.store.entity; + +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Table(name = "region") +@Builder +public class Region extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name" , nullable = false) + private String name; + + @OneToMany(mappedBy = "region") + private List storeList = 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..81ca55d --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/entity/Store.java @@ -0,0 +1,48 @@ +package com.example.umc9th.domain.store.entity; + + +import com.example.umc9th.domain.mission.entity.Mission; +import com.example.umc9th.domain.review.entity.Review; +import com.example.umc9th.domain.store.enums.StoreStatus; +import com.example.umc9th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Table(name = "store") +@Builder +public class Store extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "region_id") + private Region region; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "address", nullable = false) + private String address; + + @Column(name = "rating", nullable = false) + private Double rating; + + @Column(name = "status", nullable = false) + @Enumerated(EnumType.STRING) + private StoreStatus status; + + @OneToMany(mappedBy = "store", cascade = CascadeType.REMOVE) + private List missionList = new ArrayList<>(); + + @OneToMany(mappedBy = "store") + private List reviewList = new ArrayList<>(); +} diff --git a/src/main/java/com/example/umc9th/domain/store/enums/StoreStatus.java b/src/main/java/com/example/umc9th/domain/store/enums/StoreStatus.java new file mode 100644 index 0000000..234d7e0 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/enums/StoreStatus.java @@ -0,0 +1,5 @@ +package com.example.umc9th.domain.store.enums; + +public enum StoreStatus { + OPEN,CLOSED,PREPARED,BREAK_TIME,NONE +} 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..a6e94bc --- /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..98e2a02 --- /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.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +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..42194ae --- /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.BaseErrorCode; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum StoreSuccessCode implements BaseErrorCode { + NOT_FOUND(HttpStatus.CREATED, + "STORE201_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..28c3249 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/store/repository/StoreRepository.java @@ -0,0 +1,9 @@ +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; + +public interface StoreRepository extends JpaRepository { + +} 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..851510f --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/controller/TestController.java @@ -0,0 +1,44 @@ +package com.example.umc9th.domain.test.controller; + +import com.example.umc9th.domain.test.converter.TestConverter; +import com.example.umc9th.domain.test.dto.res.TestResDTO; +import com.example.umc9th.domain.test.service.query.TestQueryService; +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralSuccessCode; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/temp") +public class TestController { + + private final TestQueryService testQueryService; + + @GetMapping("/test") + public ApiResponse test() { + // 응답 코드 정의 + 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..af81183 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/converter/TestConverter.java @@ -0,0 +1,24 @@ +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() + .testString(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..9f13f52 --- /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 testString; + } + + @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..7264f21 --- /dev/null +++ b/src/main/java/com/example/umc9th/domain/test/exception/code/TestErrorCode.java @@ -0,0 +1,19 @@ +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; +} \ No newline at end of file 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..a6419ab --- /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); +} \ No newline at end of file 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..4097085 --- /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); + } + } +} \ No newline at end of file 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..2a6f985 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/annotation/ExistFoods.java @@ -0,0 +1,20 @@ +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/apiPayload/ApiResponse.java b/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java new file mode 100644 index 0000000..f5392eb --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/ApiResponse.java @@ -0,0 +1,37 @@ +package com.example.umc9th.global.apiPayload; + +import com.example.umc9th.global.apiPayload.code.BaseErrorCode; +import com.example.umc9th.global.apiPayload.code.BaseSuccessCode; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +@JsonPropertyOrder({"isSuccess", "code", "message", "result"}) +public class ApiResponse { + + @JsonProperty("isSuccess") + private final Boolean isSuccess; + + @JsonProperty("code") + private final String code; + + @JsonProperty("message") + private final String message; + + @JsonProperty("result") + private T result; + + // 성공한 경우 (result 포함) + public static ApiResponse onSuccess(BaseSuccessCode code, T result) { + return new ApiResponse<>(true, code.getCode(), code.getMessage(), result); + } + + + // 실패한 경우 (result 포함) + public static ApiResponse onFailure(BaseErrorCode code, T result) { + return new ApiResponse<>(false, code.getCode(), code.getMessage(), result); + } +} diff --git a/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..6509ef0 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralErrorCode.java @@ -0,0 +1,31 @@ +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{ + + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, + "COMMON500_1", + "예기치 않은 서버 에러가 발생했습니다."), + BAD_REQUEST(HttpStatus.BAD_REQUEST, + "COMMON400_1", + "잘못된 요청입니다."), + UNAUTHORIZED(HttpStatus.UNAUTHORIZED, + "AUTH401_1", + "인증이 필요합니다."), + FORBIDDEN(HttpStatus.FORBIDDEN, + "AUTH403_1", + "요청이 거부되었습니다."), + NOT_FOUND(HttpStatus.NOT_FOUND, + "COMMON404_1", + "요청한 리소스를 찾을 수 없습니다."), + ; + + 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..3b9b00b --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/code/GeneralSuccessCode.java @@ -0,0 +1,31 @@ +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_1", + "리소스를 성공적으로 생성했습니다."), + + ACCEPTED(HttpStatus.ACCEPTED, + "COMMON202_1", + "요청이 성공적으로 접수되었습니다."), + + NO_CONTENT(HttpStatus.NO_CONTENT, + "COMMON204_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/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/handler/GeneralExceptionAdvice.java b/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java new file mode 100644 index 0000000..05a8f59 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/apiPayload/handler/GeneralExceptionAdvice.java @@ -0,0 +1,62 @@ +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 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 { + + // 컨트롤러 메서드에서 @Valid 어노테이션 사용하여 DTO 유효성 검사 수행 + @ExceptionHandler + protected ResponseEntity>> handleMethodArgumentNotValidException( + MethodArgumentNotValidException ex + ) { + // 검사에 실패한 필드와 메시지 저장하는 Map + HashMap errors = new HashMap<>(); + ex.getBindingResult().getFieldErrors().forEach(error -> + errors.put(error.getField(), error.getDefaultMessage())); + + GeneralErrorCode code = GeneralErrorCode.NOT_FOUND; + ApiResponse> errorResponse = ApiResponse.onFailure(code, errors); + + return ResponseEntity.status(code.getStatus()).body(errorResponse); + } + + // 애플리케이션에서 발생하는 커스텀 예외를 처리 + @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() + ) + ); + } +} diff --git a/src/main/java/com/example/umc9th/global/auth/AuthenticationEntryPointImpl.java b/src/main/java/com/example/umc9th/global/auth/AuthenticationEntryPointImpl.java new file mode 100644 index 0000000..e2d01f4 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/AuthenticationEntryPointImpl.java @@ -0,0 +1,29 @@ +package com.example.umc9th.global.auth; + +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralErrorCode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.ServletException; +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, ServletException { + 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/auth/JwtAuthFilter.java b/src/main/java/com/example/umc9th/global/auth/JwtAuthFilter.java new file mode 100644 index 0000000..33a6b2c --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/JwtAuthFilter.java @@ -0,0 +1,56 @@ +package com.example.umc9th.global.auth; + +import com.example.umc9th.global.apiPayload.ApiResponse; +import com.example.umc9th.global.apiPayload.code.GeneralErrorCode; +import com.example.umc9th.global.auth.entity.CustomUserDetailsService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@RequiredArgsConstructor +public class JwtAuthFilter extends OncePerRequestFilter { + + private final JwtUtil jwtUtil; + private final CustomUserDetailsService customUserDetailsService; + + @Override + protected void doFilterInternal( + @NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain) + throws ServletException, IOException { + + + String token = request.getHeader("Authorization"); + if (token == null || !token.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + return; + } + token = token.replace("Bearer ", ""); + + if (jwtUtil.isValid(token)) { + String email = jwtUtil.getEmail(token); + UserDetails user = customUserDetailsService.loadUserByUsername(email); + + Authentication auth = new UsernamePasswordAuthenticationToken( + user, + null, + user.getAuthorities() + ); + SecurityContextHolder.getContext().setAuthentication(auth); + } + filterChain.doFilter(request, response); + } + } + diff --git a/src/main/java/com/example/umc9th/global/auth/JwtUtil.java b/src/main/java/com/example/umc9th/global/auth/JwtUtil.java new file mode 100644 index 0000000..00578d1 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/JwtUtil.java @@ -0,0 +1,80 @@ +package com.example.umc9th.global.auth; + +import com.example.umc9th.global.auth.entity.CustomUserDetails; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; +import java.util.stream.Collectors; + +@Component +public class JwtUtil { + + private final SecretKey secretKey; + private final Duration accessExpiration; + + public JwtUtil( + @Value("${jwt.token.secretKey}") String secret, + @Value("${jwt.token.expiration.access}") Long accessExpiration + ) { + this.secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); + this.accessExpiration = Duration.ofMillis(accessExpiration); + } + + public String createAccessToken(CustomUserDetails user) { + return createToken(user, accessExpiration); + } + + public String getEmail(String token) { + try { + return getClaims(token).getPayload().getSubject(); + } catch (JwtException e) { + return null; + } + } + + 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()) + .claim("role",authorities) + .claim("email",user.getUsername()) + .issuedAt(Date.from(now)) + .expiration(Date.from(now.plus(expiration))) + .signWith(secretKey) + .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/auth/dto/MemberReqDTO.java b/src/main/java/com/example/umc9th/global/auth/dto/MemberReqDTO.java new file mode 100644 index 0000000..92b51b8 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/dto/MemberReqDTO.java @@ -0,0 +1,13 @@ +package com.example.umc9th.global.auth.dto; + +import jakarta.validation.constraints.NotBlank; + +public class MemberReqDTO { + + public record LoginDTO( + @NotBlank + String email, + @NotBlank + String password + ){} +} diff --git a/src/main/java/com/example/umc9th/global/auth/dto/MemberResDTO.java b/src/main/java/com/example/umc9th/global/auth/dto/MemberResDTO.java new file mode 100644 index 0000000..4155633 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/dto/MemberResDTO.java @@ -0,0 +1,12 @@ +package com.example.umc9th.global.auth.dto; + +import lombok.Builder; + +public class MemberResDTO { + + @Builder + public record LoginDTO( + Long memberId, + String accessToken + ){} +} diff --git a/src/main/java/com/example/umc9th/global/auth/entity/CustomUserDetails.java b/src/main/java/com/example/umc9th/global/auth/entity/CustomUserDetails.java new file mode 100644 index 0000000..80749ee --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/entity/CustomUserDetails.java @@ -0,0 +1,31 @@ +package com.example.umc9th.global.auth.entity; + +import com.example.umc9th.domain.member.entity.Member; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +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(new SimpleGrantedAuthority(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/auth/entity/CustomUserDetailsService.java b/src/main/java/com/example/umc9th/global/auth/entity/CustomUserDetailsService.java new file mode 100644 index 0000000..86a75b8 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/entity/CustomUserDetailsService.java @@ -0,0 +1,25 @@ +package com.example.umc9th.global.auth.entity; + +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 = memberRepository.findByEmail(username) + .orElseThrow(() -> new MemberException(MemberErrorCode.NOT_FOUND)); + return new CustomUserDetails(member); + } +} diff --git a/src/main/java/com/example/umc9th/global/auth/enums/Role.java b/src/main/java/com/example/umc9th/global/auth/enums/Role.java new file mode 100644 index 0000000..673e30c --- /dev/null +++ b/src/main/java/com/example/umc9th/global/auth/enums/Role.java @@ -0,0 +1,5 @@ +package com.example.umc9th.global.auth.enums; + +public enum Role { + ROLE_ADMIN, ROLE_USER +} diff --git a/src/main/java/com/example/umc9th/global/config/QueryDslConfig.java b/src/main/java/com/example/umc9th/global/config/QueryDslConfig.java new file mode 100644 index 0000000..4f203d1 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/config/QueryDslConfig.java @@ -0,0 +1,19 @@ +package com.example.umc9th.global.config; + +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class QueryDslConfig { + + @PersistenceContext + private EntityManager entityManager; + + @Bean + public JPAQueryFactory jpaQueryFactory() { + return new JPAQueryFactory(entityManager); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc9th/global/config/SecurityConfig.java b/src/main/java/com/example/umc9th/global/config/SecurityConfig.java new file mode 100644 index 0000000..1f6c259 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/config/SecurityConfig.java @@ -0,0 +1,68 @@ +package com.example.umc9th.global.config; + +import com.example.umc9th.global.auth.AuthenticationEntryPointImpl; +import com.example.umc9th.global.auth.JwtAuthFilter; +import com.example.umc9th.global.auth.JwtUtil; +import com.example.umc9th.global.auth.entity.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 SecurityConfig { + + private final JwtUtil jwtUtil; + private final CustomUserDetailsService customUserDetailsService; + + private final String[] allowUris = { + "/members/login", + "/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) + .addFilterBefore(jwtAuthFilter(), UsernamePasswordAuthenticationFilter.class) + .csrf(AbstractHttpConfigurer::disable) + .logout(logout->logout + .logoutUrl("/logout") + .logoutSuccessUrl("/login?logout") + .permitAll() + ) + .exceptionHandling(exception -> exception.authenticationEntryPoint(authenticationEntryPoint())); + return http.build(); + } + + @Bean + public JwtAuthFilter jwtAuthFilter() { + return new JwtAuthFilter(jwtUtil, customUserDetailsService); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public AuthenticationEntryPoint authenticationEntryPoint() { + return new AuthenticationEntryPointImpl(); + } +} diff --git a/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..0795172 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/config/SwaggerConfig.java @@ -0,0 +1,35 @@ +package com.example.umc9th.global.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { + + @Bean + public OpenAPI swagger() { + Info info = new Info().title("Project").description("Project Swagger").version("0.0.1"); + + 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/entity/BaseEntity.java b/src/main/java/com/example/umc9th/global/entity/BaseEntity.java new file mode 100644 index 0000000..47563e5 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/entity/BaseEntity.java @@ -0,0 +1,27 @@ +package com.example.umc9th.global.entity; + +import com.querydsl.core.annotations.QuerySupertype; +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 +@QuerySupertype +public class BaseEntity { + + @CreatedDate + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; +} 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..d87b1e9 --- /dev/null +++ b/src/main/java/com/example/umc9th/global/validator/FoodExistValidator.java @@ -0,0 +1,31 @@ +package com.example.umc9th.global.validator; + +import com.example.umc9th.domain.member.exception.code.FoodErrorCode; +import com.example.umc9th.domain.member.repository.FoodRepository; +import com.example.umc9th.global.annotation.ExistFoods; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class FoodExistValidator implements ConstraintValidator> { + + private final FoodRepository foodRepository; + + @Override + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = values.stream() + .allMatch(value -> foodRepository.existsById(value)); + + if (!isValid) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(FoodErrorCode.NOT_FOUND.getMessage()).addConstraintViolation(); + + } + return isValid; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..3dda363 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,25 @@ +spring: + application: + name: "umc9th" # "umc9th" + + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver # MySQL JDBC ???? ??? ?? + url: ${DB_URL} # jdbc:mysql://localhost:3306/{???????} + username: ${DB_USER} # MySQL ?? ?? + password: ${DB_PW} # MySQL ???? + + jpa: + database: mysql # ??? ?????? ?? ?? (MySQL) + database-platform: org.hibernate.dialect.MySQLDialect # Hibernate?? ??? MySQL ??(dialect) ?? + show-sql: true # ??? SQL ??? ??? ???? ?? ?? + hibernate: + ddl-auto: update # ?????? ?? ? ?????? ???? ??? ?? + properties: + hibernate: + format_sql: true # ???? SQL ??? ?? ?? ???spring.application.name=umc9th + +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() { + } + +} diff --git a/src/test/java/com/example/umc9th/domain/member/service/MemberServiceTest.java b/src/test/java/com/example/umc9th/domain/member/service/MemberServiceTest.java new file mode 100644 index 0000000..a4dc238 --- /dev/null +++ b/src/test/java/com/example/umc9th/domain/member/service/MemberServiceTest.java @@ -0,0 +1,66 @@ +package com.example.umc9th.domain.member.service; + +import com.example.umc9th.domain.member.dto.MemberInfoResponseDTO; +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.repository.MemberRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.NoSuchElementException; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class MemberServiceTest { + + @InjectMocks // 테스트 대상 서비스 + private MemberService memberService; + + @Mock // Mocking 할 Repository + private MemberRepository memberRepository; + + @Test + @DisplayName("마이페이지 정보 조회 성공 테스트") + void getMemberInfo_success() { + // Given + Long memberId = 1L; + Member mockMember = Member.builder() + .id(memberId) + .name("jjy0107") + .email("test@naver.com") + .phoneNumber("010-1234-5678") + .point(2500) + .build(); + + // Mocking 설정: findById 호출 시 mockMember 반환 + when(memberRepository.findById(memberId)).thenReturn(Optional.of(mockMember)); + + // When + MemberInfoResponseDTO result = memberService.getMemberInfo(memberId); + + // Then + assertThat(result.getNickname()).isEqualTo("jjy0107"); + assertThat(result.getEmail()).isEqualTo("test@naver.com"); + } + + @Test + @DisplayName("마이페이지 정보 조회 실패 (회원 없음) 테스트") + void getMemberInfo_failure_not_found() { + // Given + Long nonExistentId = 999L; + + // Mocking 설정: findById 호출 시 빈 Optional 반환 + when(memberRepository.findById(nonExistentId)).thenReturn(Optional.empty()); + + // When & Then + // NoSuchElementException이 발생하는지 확인 + assertThrows(NoSuchElementException.class, () -> memberService.getMemberInfo(nonExistentId)); + } +} \ No newline at end of file diff --git a/src/test/java/com/example/umc9th/domain/mission/service/MissionServiceTest.java b/src/test/java/com/example/umc9th/domain/mission/service/MissionServiceTest.java new file mode 100644 index 0000000..55016f8 --- /dev/null +++ b/src/test/java/com/example/umc9th/domain/mission/service/MissionServiceTest.java @@ -0,0 +1,103 @@ +package com.example.umc9th.domain.mission.service; + +import com.example.umc9th.domain.mission.enums.MemberMissionStatus; +import com.example.umc9th.domain.mission.dto.ChallengeMissionResponseDTO; +import com.example.umc9th.domain.mission.dto.HomeMissionResponseDTO; +import com.example.umc9th.domain.mission.dto.MissionResponseDTO; +import com.example.umc9th.domain.mission.repository.MemberMissionRepository; +import com.example.umc9th.domain.mission.repository.MissionRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class MissionServiceTest { + + @InjectMocks + private MissionService missionService; + + @Mock + private MemberMissionRepository memberMissionRepository; + @Mock + private MissionRepository missionRepository; + + @Test + @DisplayName("진행 완료 미션 목록 조회 테스트") + void getCompletedMissionsTest() { + // Given + Long memberId = 1L; + Pageable pageable = PageRequest.of(0, 5); + + MissionResponseDTO completedMission = MissionResponseDTO.builder() + .missionStatus(MemberMissionStatus.COMPLETED.name()) + .storeName("완료가게").build(); + + Page mockPage = new PageImpl<>(List.of(completedMission), pageable, 1); + + // Mocking 설정 + when(memberMissionRepository.findMemberMissionsByStatus( + eq(memberId), + eq(MemberMissionStatus.COMPLETED), + eq(pageable))) + .thenReturn(mockPage); + + // When + Page result = missionService.getCompletedMissions(memberId, pageable); + + // Then + assertThat(result.getTotalElements()).isEqualTo(1); + assertThat(result.getContent().get(0).getStoreName()).isEqualTo("완료가게"); + } + + @Test + @DisplayName("홈 화면 정보 조회 및 통계 테스트") + void getHomeMissionsTest() { + // Given + Long memberId = 1L; + Long regionId = 10L; + Pageable pageable = PageRequest.of(0, 5); + + // Mock 1: 도전 가능 미션 목록 + ChallengeMissionResponseDTO missionDto = ChallengeMissionResponseDTO.builder().missionId(5L).storeName("도전가게").build(); + Page mockMissionPage = new PageImpl<>(List.of(missionDto), pageable, 10); // 총 10개 가정 + + // Mock 2: 완료된 미션 개수 + Long completedCount = 7L; // 7개 완료 가정 + + // Mocking 설정 + when(missionRepository.findChallengeableMissionsByRegion( + eq(regionId), any(LocalDateTime.class), eq(pageable))) + .thenReturn(mockMissionPage); + + when(memberMissionRepository.countCompletedMissionsByMemberAndRegion( + eq(memberId), eq(regionId))) + .thenReturn(completedCount); + + // When + HomeMissionResponseDTO result = missionService.getHomeMissions(memberId, regionId, pageable); + + // Then + // 통계 검증: 7/10 + assertThat(result.getCompletedCount()).isEqualTo(7L); + assertThat(result.getTotalCount()).isEqualTo(10L); // PageImpl의 TotalElements + + // 목록 검증 + assertThat(result.getMissionList().getContent()).hasSize(1); + assertThat(result.getMissionList().getContent().get(0).getStoreName()).isEqualTo("도전가게"); + } +} \ No newline at end of file diff --git a/src/test/java/com/example/umc9th/domain/review/service/ReviewServiceTest.java b/src/test/java/com/example/umc9th/domain/review/service/ReviewServiceTest.java new file mode 100644 index 0000000..71c82c4 --- /dev/null +++ b/src/test/java/com/example/umc9th/domain/review/service/ReviewServiceTest.java @@ -0,0 +1,116 @@ +package com.example.umc9th.domain.review.service; + +import com.example.umc9th.domain.member.entity.Member; +import com.example.umc9th.domain.member.repository.MemberRepository; +import com.example.umc9th.domain.review.dto.ReviewRequestDTO; +import com.example.umc9th.domain.review.dto.ReviewResponseDTO; +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.repository.StoreRepository; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ReviewServiceTest { + + @InjectMocks + private ReviewService reviewService; + + @Mock + private ReviewRepository reviewRepository; + @Mock + private MemberRepository memberRepository; + @Mock + private StoreRepository storeRepository; + + + @Test + @DisplayName("리뷰 작성 성공 테스트") + void createReview_success() { + // Given + Long storeId = 1L; + Long memberId = 2L; + ReviewRequestDTO request = new ReviewRequestDTO("새로운 리뷰 내용", 5.0); + + // Mock 엔티티 생성 + Member mockMember = Member.builder().id(memberId).build(); + Store mockStore = Store.builder().id(storeId).build(); + Review mockReview = Review.builder().id(10L).member(mockMember).store(mockStore).content(request.getContent()).rating(request.getRating()).build(); + + // Mocking 설정 + when(memberRepository.findById(memberId)).thenReturn(Optional.of(mockMember)); // 회원 조회 성공 + when(storeRepository.findById(storeId)).thenReturn(Optional.of(mockStore)); // 가게 조회 성공 + when(reviewRepository.save(any(Review.class))).thenReturn(mockReview); // save 호출 시 mockReview 반환 + + // When + Review createdReview = reviewService.createReview(storeId, memberId, request); + + // Then + // 1. save 메서드가 호출되었는지 검증 + verify(reviewRepository).save(any(Review.class)); + // 2. 반환된 리뷰 내용 검증 + assertThat(createdReview.getContent()).isEqualTo("새로운 리뷰 내용"); + assertThat(createdReview.getRating()).isEqualTo(5.0); + } + + @Test + @DisplayName("작성한 리뷰 목록 조회 테스트") + void getMyReviewsTest() { + // Given + Long memberId = 1L; + + // JPQL 쿼리 결과로 가정할 Mock DTO 리스트 + List mockReviews = List.of( + ReviewResponseDTO.builder().storeName("신승호").content("맛있어요!").rating(4.5).build(), + ReviewResponseDTO.builder().storeName("버거킹").content("별로네요.").rating(2.0).build() + ); + + // Mocking 설정: reviewRepository.findMemberReviews(memberId) 호출 시 mockReviews 반환 + when(reviewRepository.findMemberReviews(memberId)).thenReturn(mockReviews); + + // When + List result = reviewService.getMyReviews(memberId); + + // Then + // 1. 결과 리스트 크기 검증 + assertThat(result).hasSize(2); + // 2. 리뷰 내용이 예상대로 포함되어 있는지 검증 (순서 무관) + assertThat(result.stream().map(ReviewResponseDTO::getContent)) + .containsExactlyInAnyOrder("맛있어요!", "별로네요."); + } + + + @Test + @DisplayName("리뷰 작성 실패 (회원 없음) 테스트") + void createReview_failure_member_not_found() { + // Given + Long nonExistentMemberId = 999L; + Long storeId = 1L; // 가게 ID는 사용되지 않지만, 메서드 호출을 위해 필요 + ReviewRequestDTO request = new ReviewRequestDTO("내용", 4.0); + + // Mocking 설정: 회원 조회 실패 (가장 먼저 발생하는 실패 조건을 설정) + // storeRepository.findById에 대한 Mocking은 제거합니다. + when(memberRepository.findById(nonExistentMemberId)).thenReturn(Optional.empty()); + + // When & Then + // 회원 조회 실패 시 바로 예외가 발생하는지 검증 + assertThrows(NoSuchElementException.class, + () -> reviewService.createReview(storeId, nonExistentMemberId, request)); + } + +} \ No newline at end of file