diff --git a/week5/spring/.gitignore b/week5/spring/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/week5/spring/.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/week5/spring/build.gradle b/week5/spring/build.gradle new file mode 100644 index 0000000..b9dba4c --- /dev/null +++ b/week5/spring/build.gradle @@ -0,0 +1,97 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.4' + id 'io.spring.dependency-management' version '1.1.6' + //id "com.ewerk.gradle.plugins.querydsl" version "1.0.10" +} + +group = 'umc' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // Jakarta Servlet API (Spring Boot 3.x 호환) + implementation 'jakarta.servlet:jakarta.servlet-api:5.0.0' + + implementation 'mysql:mysql-connector-java:8.0.33' // MySQL 드라이버 추가 + + // 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" + + // Jackson +// implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.3' +// implementation 'com.fasterxml.jackson.core:jackson-annotations:2.13.3' +// implementation 'com.fasterxml.jackson.core:jackson-core:2.13.3' + + // Lombok + compileOnly 'org.projectlombok:lombok:1.18.22' + annotationProcessor 'org.projectlombok:lombok:1.18.22' + + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // ANTLR 툴과 런타임 버전이 맞추깅 + implementation 'org.antlr:antlr4:4.13.0' + +} + +//sourceSets { +// main { +// java { +// srcDirs = ['src/main/java', 'src/main/resources'] +// } +// } +//} + +tasks.named('test') { + useJUnitPlatform() +} + +// Querydsl 설정부 +//def generated = 'src/main/generated' +// +//querydsl { +// jpa = true +// querydslSourcesDir = generated +//} +//sourceSets { +// main.java.srcDir generated +//} +// +//compileQuerydsl{ +// options.annotationProcessorPath = configurations.querydsl +//} +// +//configurations { +// compileOnly { +// extendsFrom annotationProcessor +// } +// querydsl.extendsFrom compileClasspath +//} + +clean { + delete file('src/main/generated') +} \ No newline at end of file diff --git a/week5/spring/gradle/wrapper/gradle-wrapper.jar b/week5/spring/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/week5/spring/gradle/wrapper/gradle-wrapper.jar differ diff --git a/week5/spring/gradle/wrapper/gradle-wrapper.properties b/week5/spring/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df97d72 --- /dev/null +++ b/week5/spring/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/week5/spring/gradlew b/week5/spring/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/week5/spring/gradlew @@ -0,0 +1,252 @@ +#!/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 +' "$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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# 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, 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" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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/week5/spring/gradlew.bat b/week5/spring/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/week5/spring/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=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +: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/week5/spring/settings.gradle b/week5/spring/settings.gradle new file mode 100644 index 0000000..ebf1ef8 --- /dev/null +++ b/week5/spring/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'spring' diff --git a/week5/spring/src/main/generated/umc/study/domain/QFood.java b/week5/spring/src/main/generated/umc/study/domain/QFood.java new file mode 100644 index 0000000..01e1500 --- /dev/null +++ b/week5/spring/src/main/generated/umc/study/domain/QFood.java @@ -0,0 +1,44 @@ +package umc.study.domain; + +import static com.querydsl.core.types.PathMetadataFactory.*; + +import com.querydsl.core.types.dsl.*; + +import com.querydsl.core.types.PathMetadata; +import javax.annotation.processing.Generated; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.PathInits; + + +/** + * QFood is a Querydsl query type for Food + */ +@Generated("com.querydsl.codegen.DefaultEntitySerializer") +public class QFood extends EntityPathBase { + + private static final long serialVersionUID = 478578784L; + + public static final QFood food = new QFood("food"); + + public final StringPath foodName = createString("foodName"); + + public final NumberPath id = createNumber("id", Long.class); + + public final ListPath storeList = this.createList("storeList", Store.class, QStore.class, PathInits.DIRECT2); + + public final ListPath userFavoriteFoodsList = this.createList("userFavoriteFoodsList", UserFavoriteFoods.class, QUserFavoriteFoods.class, PathInits.DIRECT2); + + public QFood(String variable) { + super(Food.class, forVariable(variable)); + } + + public QFood(Path path) { + super(path.getType(), path.getMetadata()); + } + + public QFood(PathMetadata metadata) { + super(Food.class, metadata); + } + +} + diff --git a/week5/spring/src/main/generated/umc/study/domain/QMission.java b/week5/spring/src/main/generated/umc/study/domain/QMission.java new file mode 100644 index 0000000..f22f0c7 --- /dev/null +++ b/week5/spring/src/main/generated/umc/study/domain/QMission.java @@ -0,0 +1,63 @@ +package umc.study.domain; + +import static com.querydsl.core.types.PathMetadataFactory.*; + +import com.querydsl.core.types.dsl.*; + +import com.querydsl.core.types.PathMetadata; +import javax.annotation.processing.Generated; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.PathInits; + + +/** + * QMission is a Querydsl query type for Mission + */ +@Generated("com.querydsl.codegen.DefaultEntitySerializer") +public class QMission extends EntityPathBase { + + private static final long serialVersionUID = -200839606L; + + private static final PathInits INITS = PathInits.DIRECT2; + + public static final QMission mission = new QMission("mission"); + + public final DateTimePath deadline = createDateTime("deadline", java.time.LocalDateTime.class); + + public final NumberPath id = createNumber("id", Long.class); + + public final DatePath inactiveDate = createDate("inactiveDate", java.time.LocalDate.class); + + public final StringPath missionDescription = createString("missionDescription"); + + public final NumberPath missionPoint = createNumber("missionPoint", Integer.class); + + public final EnumPath status = createEnum("status", umc.study.domain.enums.Status.class); + + public final QStore store; + + public final ListPath userMissionList = this.createList("userMissionList", UserMission.class, QUserMission.class, PathInits.DIRECT2); + + public QMission(String variable) { + this(Mission.class, forVariable(variable), INITS); + } + + public QMission(Path path) { + this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS)); + } + + public QMission(PathMetadata metadata) { + this(metadata, PathInits.getFor(metadata, INITS)); + } + + public QMission(PathMetadata metadata, PathInits inits) { + this(Mission.class, metadata, inits); + } + + public QMission(Class type, PathMetadata metadata, PathInits inits) { + super(type, metadata, inits); + this.store = inits.isInitialized("store") ? new QStore(forProperty("store"), inits.get("store")) : null; + } + +} + diff --git a/week5/spring/src/main/generated/umc/study/domain/QReview.java b/week5/spring/src/main/generated/umc/study/domain/QReview.java new file mode 100644 index 0000000..8f2df4d --- /dev/null +++ b/week5/spring/src/main/generated/umc/study/domain/QReview.java @@ -0,0 +1,64 @@ +package umc.study.domain; + +import static com.querydsl.core.types.PathMetadataFactory.*; + +import com.querydsl.core.types.dsl.*; + +import com.querydsl.core.types.PathMetadata; +import javax.annotation.processing.Generated; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.PathInits; + + +/** + * QReview is a Querydsl query type for Review + */ +@Generated("com.querydsl.codegen.DefaultEntitySerializer") +public class QReview extends EntityPathBase { + + private static final long serialVersionUID = 687241946L; + + private static final PathInits INITS = PathInits.DIRECT2; + + public static final QReview review = new QReview("review"); + + public final DateTimePath createdAt = createDateTime("createdAt", java.time.LocalDateTime.class); + + public final NumberPath id = createNumber("id", Long.class); + + public final StringPath reviewContent = createString("reviewContent"); + + public final StringPath reviewImg = createString("reviewImg"); + + public final EnumPath reviewScope = createEnum("reviewScope", umc.study.domain.enums.ReviewScope.class); + + public final QStore store; + + public final DateTimePath updatedAt = createDateTime("updatedAt", java.time.LocalDateTime.class); + + public final QUser user; + + public QReview(String variable) { + this(Review.class, forVariable(variable), INITS); + } + + public QReview(Path path) { + this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS)); + } + + public QReview(PathMetadata metadata) { + this(metadata, PathInits.getFor(metadata, INITS)); + } + + public QReview(PathMetadata metadata, PathInits inits) { + this(Review.class, metadata, inits); + } + + public QReview(Class type, PathMetadata metadata, PathInits inits) { + super(type, metadata, inits); + this.store = inits.isInitialized("store") ? new QStore(forProperty("store"), inits.get("store")) : null; + this.user = inits.isInitialized("user") ? new QUser(forProperty("user")) : null; + } + +} + diff --git a/week5/spring/src/main/generated/umc/study/domain/QStore.java b/week5/spring/src/main/generated/umc/study/domain/QStore.java new file mode 100644 index 0000000..0038024 --- /dev/null +++ b/week5/spring/src/main/generated/umc/study/domain/QStore.java @@ -0,0 +1,69 @@ +package umc.study.domain; + +import static com.querydsl.core.types.PathMetadataFactory.*; + +import com.querydsl.core.types.dsl.*; + +import com.querydsl.core.types.PathMetadata; +import javax.annotation.processing.Generated; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.PathInits; + + +/** + * QStore is a Querydsl query type for Store + */ +@Generated("com.querydsl.codegen.DefaultEntitySerializer") +public class QStore extends EntityPathBase { + + private static final long serialVersionUID = 1963195679L; + + private static final PathInits INITS = PathInits.DIRECT2; + + public static final QStore store = new QStore("store"); + + public final DateTimePath createdAt = createDateTime("createdAt", java.time.LocalDateTime.class); + + public final QFood food; + + public final NumberPath id = createNumber("id", Long.class); + + public final DatePath inactiveDate = createDate("inactiveDate", java.time.LocalDate.class); + + public final ListPath missionList = this.createList("missionList", Mission.class, QMission.class, PathInits.DIRECT2); + + public final ListPath reviewList = this.createList("reviewList", Review.class, QReview.class, PathInits.DIRECT2); + + public final EnumPath status = createEnum("status", umc.study.domain.enums.Status.class); + + public final StringPath storeLocation = createString("storeLocation"); + + public final StringPath storeName = createString("storeName"); + + public final NumberPath storeScope = createNumber("storeScope", java.math.BigDecimal.class); + + public final DateTimePath updatedAt = createDateTime("updatedAt", java.time.LocalDateTime.class); + + public QStore(String variable) { + this(Store.class, forVariable(variable), INITS); + } + + public QStore(Path path) { + this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS)); + } + + public QStore(PathMetadata metadata) { + this(metadata, PathInits.getFor(metadata, INITS)); + } + + public QStore(PathMetadata metadata, PathInits inits) { + this(Store.class, metadata, inits); + } + + public QStore(Class type, PathMetadata metadata, PathInits inits) { + super(type, metadata, inits); + this.food = inits.isInitialized("food") ? new QFood(forProperty("food")) : null; + } + +} + diff --git a/week5/spring/src/main/generated/umc/study/domain/QUser.java b/week5/spring/src/main/generated/umc/study/domain/QUser.java new file mode 100644 index 0000000..f5bc5c8 --- /dev/null +++ b/week5/spring/src/main/generated/umc/study/domain/QUser.java @@ -0,0 +1,68 @@ +package umc.study.domain; + +import static com.querydsl.core.types.PathMetadataFactory.*; + +import com.querydsl.core.types.dsl.*; + +import com.querydsl.core.types.PathMetadata; +import javax.annotation.processing.Generated; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.PathInits; + + +/** + * QUser is a Querydsl query type for User + */ +@Generated("com.querydsl.codegen.DefaultEntitySerializer") +public class QUser extends EntityPathBase { + + private static final long serialVersionUID = 479029197L; + + public static final QUser user = new QUser("user"); + + public final DateTimePath createdAt = createDateTime("createdAt", java.time.LocalDateTime.class); + + public final EnumPath gender = createEnum("gender", umc.study.domain.enums.Gender.class); + + public final NumberPath id = createNumber("id", Long.class); + + public final DatePath inactive_date = createDate("inactive_date", java.time.LocalDate.class); + + public final ListPath reviewList = this.createList("reviewList", Review.class, QReview.class, PathInits.DIRECT2); + + public final EnumPath status = createEnum("status", umc.study.domain.enums.Status.class); + + public final DateTimePath updatedAt = createDateTime("updatedAt", java.time.LocalDateTime.class); + + public final StringPath user_name = createString("user_name"); + + public final StringPath userAddress = createString("userAddress"); + + public final DatePath userBirth = createDate("userBirth", java.time.LocalDate.class); + + public final StringPath userEmail = createString("userEmail"); + + public final ListPath userFavoriteFoodsList = this.createList("userFavoriteFoodsList", UserFavoriteFoods.class, QUserFavoriteFoods.class, PathInits.DIRECT2); + + public final BooleanPath userLogin = createBoolean("userLogin"); + + public final ListPath userMissionList = this.createList("userMissionList", UserMission.class, QUserMission.class, PathInits.DIRECT2); + + public final StringPath userPhone = createString("userPhone"); + + public final NumberPath userPoint = createNumber("userPoint", Integer.class); + + public QUser(String variable) { + super(User.class, forVariable(variable)); + } + + public QUser(Path path) { + super(path.getType(), path.getMetadata()); + } + + public QUser(PathMetadata metadata) { + super(User.class, metadata); + } + +} + diff --git a/week5/spring/src/main/generated/umc/study/domain/QUserFavoriteFoods.java b/week5/spring/src/main/generated/umc/study/domain/QUserFavoriteFoods.java new file mode 100644 index 0000000..a0da238 --- /dev/null +++ b/week5/spring/src/main/generated/umc/study/domain/QUserFavoriteFoods.java @@ -0,0 +1,54 @@ +package umc.study.domain; + +import static com.querydsl.core.types.PathMetadataFactory.*; + +import com.querydsl.core.types.dsl.*; + +import com.querydsl.core.types.PathMetadata; +import javax.annotation.processing.Generated; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.PathInits; + + +/** + * QUserFavoriteFoods is a Querydsl query type for UserFavoriteFoods + */ +@Generated("com.querydsl.codegen.DefaultEntitySerializer") +public class QUserFavoriteFoods extends EntityPathBase { + + private static final long serialVersionUID = -2059270964L; + + private static final PathInits INITS = PathInits.DIRECT2; + + public static final QUserFavoriteFoods userFavoriteFoods = new QUserFavoriteFoods("userFavoriteFoods"); + + public final QFood food; + + public final NumberPath id = createNumber("id", Long.class); + + public final QUser user; + + public QUserFavoriteFoods(String variable) { + this(UserFavoriteFoods.class, forVariable(variable), INITS); + } + + public QUserFavoriteFoods(Path path) { + this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS)); + } + + public QUserFavoriteFoods(PathMetadata metadata) { + this(metadata, PathInits.getFor(metadata, INITS)); + } + + public QUserFavoriteFoods(PathMetadata metadata, PathInits inits) { + this(UserFavoriteFoods.class, metadata, inits); + } + + public QUserFavoriteFoods(Class type, PathMetadata metadata, PathInits inits) { + super(type, metadata, inits); + this.food = inits.isInitialized("food") ? new QFood(forProperty("food")) : null; + this.user = inits.isInitialized("user") ? new QUser(forProperty("user")) : null; + } + +} + diff --git a/week5/spring/src/main/generated/umc/study/domain/QUserMission.java b/week5/spring/src/main/generated/umc/study/domain/QUserMission.java new file mode 100644 index 0000000..c2b12a0 --- /dev/null +++ b/week5/spring/src/main/generated/umc/study/domain/QUserMission.java @@ -0,0 +1,54 @@ +package umc.study.domain; + +import static com.querydsl.core.types.PathMetadataFactory.*; + +import com.querydsl.core.types.dsl.*; + +import com.querydsl.core.types.PathMetadata; +import javax.annotation.processing.Generated; +import com.querydsl.core.types.Path; +import com.querydsl.core.types.dsl.PathInits; + + +/** + * QUserMission is a Querydsl query type for UserMission + */ +@Generated("com.querydsl.codegen.DefaultEntitySerializer") +public class QUserMission extends EntityPathBase { + + private static final long serialVersionUID = -2044149505L; + + private static final PathInits INITS = PathInits.DIRECT2; + + public static final QUserMission userMission = new QUserMission("userMission"); + + public final NumberPath id = createNumber("id", Long.class); + + public final QMission mission; + + public final QUser user; + + public QUserMission(String variable) { + this(UserMission.class, forVariable(variable), INITS); + } + + public QUserMission(Path path) { + this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS)); + } + + public QUserMission(PathMetadata metadata) { + this(metadata, PathInits.getFor(metadata, INITS)); + } + + public QUserMission(PathMetadata metadata, PathInits inits) { + this(UserMission.class, metadata, inits); + } + + public QUserMission(Class type, PathMetadata metadata, PathInits inits) { + super(type, metadata, inits); + this.mission = inits.isInitialized("mission") ? new QMission(forProperty("mission"), inits.get("mission")) : null; + this.user = inits.isInitialized("user") ? new QUser(forProperty("user")) : null; + } + +} + diff --git a/week5/spring/src/main/java/umc/study/Application.java b/week5/spring/src/main/java/umc/study/Application.java new file mode 100644 index 0000000..54e5b41 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/Application.java @@ -0,0 +1,38 @@ +package umc.study; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import umc.study.service.StoreService.StoreQueryService; + +@SpringBootApplication +@EnableJpaAuditing +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + //@Bean +// public CommandLineRunner run(ApplicationContext context) { +// return args -> { +// StoreQueryService storeService = context.getBean(StoreQueryService.class); +// +// // 파라미터 값 설정ㅈ +// String name = "요아정"; +// Float score = 4.0f; +// +// // 쿼리 메서드 호출 및 쿼리 문자열과 파라미터 출력 +// System.out.println("Executing findStoresByNameAndScore with parameters:"); +// System.out.println("Name: " + name); +// System.out.println("Score: " + score); +// +// storeService.findStoresByNameAndScore(name, score) +// .forEach(System.out::println); +// }; + //} + +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/apiPayload/ApiResponse.java b/week5/spring/src/main/java/umc/study/apiPayload/ApiResponse.java new file mode 100644 index 0000000..944169f --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/ApiResponse.java @@ -0,0 +1,39 @@ +package umc.study.apiPayload; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.AllArgsConstructor; +import lombok.Getter; +import umc.study.apiPayload.code.BaseCode; +import umc.study.apiPayload.code.status.SuccessStatus; + +@Getter +@AllArgsConstructor +@JsonPropertyOrder({"isSuccess", "code", "message", "result"}) +public class ApiResponse { + + @JsonProperty("isSuccess") + private final Boolean isSuccess; + private final String code; + private final String message; + @JsonInclude(JsonInclude.Include.NON_NULL) + private T result; + + + // 성공한 경우 응답 생성 + + public static ApiResponse onSuccess(T result){ + return new ApiResponse<>(true, SuccessStatus._OK.getCode() , SuccessStatus._OK.getMessage(), result); + } + + public static ApiResponse of(BaseCode code, T result){ + return new ApiResponse<>(true, code.getReasonHttpStatus().getCode() , code.getReasonHttpStatus().getMessage(), result); + } + + + // 실패한 경우 응답 생성 + public static ApiResponse onFailure(String code, String message, T data){ + return new ApiResponse<>(false, code, message, data); + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/apiPayload/code/BaseCode.java b/week5/spring/src/main/java/umc/study/apiPayload/code/BaseCode.java new file mode 100644 index 0000000..3c3dd87 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/code/BaseCode.java @@ -0,0 +1,8 @@ +package umc.study.apiPayload.code; + +public interface BaseCode { + + ReasonDTO getReason(); + + ReasonDTO getReasonHttpStatus(); +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/code/BaseErrorCode.java b/week5/spring/src/main/java/umc/study/apiPayload/code/BaseErrorCode.java new file mode 100644 index 0000000..89b4fb8 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/code/BaseErrorCode.java @@ -0,0 +1,8 @@ +package umc.study.apiPayload.code; + +public interface BaseErrorCode { + + ErrorReasonDTO getReason(); + + ErrorReasonDTO getReasonHttpStatus(); +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/code/ErrorReasonDTO.java b/week5/spring/src/main/java/umc/study/apiPayload/code/ErrorReasonDTO.java new file mode 100644 index 0000000..f529728 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/code/ErrorReasonDTO.java @@ -0,0 +1,18 @@ +package umc.study.apiPayload.code; + +import lombok.Builder; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@Builder +public class ErrorReasonDTO { + + private HttpStatus httpStatus; + + private final boolean isSuccess; + private final String code; + private final String message; + + public boolean getIsSuccess(){return isSuccess;} +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/code/ReasonDTO.java b/week5/spring/src/main/java/umc/study/apiPayload/code/ReasonDTO.java new file mode 100644 index 0000000..05764b3 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/code/ReasonDTO.java @@ -0,0 +1,18 @@ +package umc.study.apiPayload.code; + +import lombok.Builder; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@Builder +public class ReasonDTO { + + private HttpStatus httpStatus; + + private final boolean isSuccess; + private final String code; + private final String message; + + public boolean getIsSuccess(){return isSuccess;} +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/code/status/ErrorStatus.java b/week5/spring/src/main/java/umc/study/apiPayload/code/status/ErrorStatus.java new file mode 100644 index 0000000..2699e12 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/code/status/ErrorStatus.java @@ -0,0 +1,57 @@ +package umc.study.apiPayload.code.status; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; +import umc.study.apiPayload.code.BaseErrorCode; +import umc.study.apiPayload.code.ErrorReasonDTO; + +@Getter +@AllArgsConstructor +public enum ErrorStatus implements BaseErrorCode { + + // 가장 일반적인 응답 + _INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON500", "서버 에러, 관리자에게 문의 바랍니다."), + _BAD_REQUEST(HttpStatus.BAD_REQUEST,"COMMON400","잘못된 요청입니다."), + _UNAUTHORIZED(HttpStatus.UNAUTHORIZED,"COMMON401","인증이 필요합니다."), + _FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON403", "금지된 요청입니다."), + + // For test + TEMP_EXCEPTION(HttpStatus.BAD_REQUEST, "TEMP4001", "이거는 테스트"), + + // FoodCategory 관련 에러 + FOOD_CATEGORY_NOT_FOUND(HttpStatus.NOT_FOUND, "FOOD4001", "해당 음식 카테고리를 찾을 수 없습니다."), + + // 멤버 관려 에러 + MEMBER_NOT_FOUND(HttpStatus.BAD_REQUEST, "MEMBER4001", "사용자가 없습니다."), + NICKNAME_NOT_EXIST(HttpStatus.BAD_REQUEST, "MEMBER4002", "닉네임은 필수 입니다."), + + // 예시,,, + ARTICLE_NOT_FOUND(HttpStatus.NOT_FOUND, "ARTICLE4001", "게시글이 없습니다."); + + + + private final HttpStatus httpStatus; + private final String code; + private final String message; + + @Override + public ErrorReasonDTO getReason() { + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .build(); + } + + @Override + public ErrorReasonDTO getReasonHttpStatus() { + return ErrorReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(false) + .httpStatus(httpStatus) + .build() + ; + } +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/code/status/SuccessStatus.java b/week5/spring/src/main/java/umc/study/apiPayload/code/status/SuccessStatus.java new file mode 100644 index 0000000..3eb4812 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/code/status/SuccessStatus.java @@ -0,0 +1,39 @@ +package umc.study.apiPayload.code.status; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; +import umc.study.apiPayload.code.BaseCode; +import umc.study.apiPayload.code.ReasonDTO; + +@Getter +@AllArgsConstructor +public enum SuccessStatus implements BaseCode { + + // 일반적인 응답 + _OK(HttpStatus.OK, "COMMON200", "성공입니다."); + + private final HttpStatus httpStatus; + private final String code; + private final String message; + + @Override + public ReasonDTO getReason() { + return ReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(true) + .build(); + } + + @Override + public ReasonDTO getReasonHttpStatus() { + return ReasonDTO.builder() + .message(message) + .code(code) + .isSuccess(true) + .httpStatus(httpStatus) + .build() + ; + } +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/exception/ExceptionAdvice.java b/week5/spring/src/main/java/umc/study/apiPayload/exception/ExceptionAdvice.java new file mode 100644 index 0000000..bf5ea92 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/exception/ExceptionAdvice.java @@ -0,0 +1,141 @@ +package umc.study.apiPayload.exception; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.ConstraintViolationException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import umc.study.apiPayload.ApiResponse; +import umc.study.apiPayload.code.ErrorReasonDTO; +import umc.study.apiPayload.code.status.ErrorStatus; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + +@Slf4j +@RestControllerAdvice(annotations = {RestController.class}) +public class ExceptionAdvice extends ResponseEntityExceptionHandler { + + + @ExceptionHandler + public ResponseEntity validation(ConstraintViolationException e, WebRequest request) { + String errorMessage = e.getConstraintViolations().stream() + .map(constraintViolation -> constraintViolation.getMessage()) + .findFirst() + .orElseThrow(() -> new RuntimeException("ConstraintViolationException 추출 도중 에러 발생")); + + return handleExceptionInternalConstraint(e, ErrorStatus.valueOf(errorMessage), HttpHeaders.EMPTY,request); + } + + @Override + public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpHeaders headers, HttpStatusCode status, WebRequest request) { + + Map errors = new LinkedHashMap<>(); + + e.getBindingResult().getFieldErrors().stream() + .forEach(fieldError -> { + String fieldName = fieldError.getField(); + String errorMessage = Optional.ofNullable(fieldError.getDefaultMessage()).orElse(""); + errors.merge(fieldName, errorMessage, (existingErrorMessage, newErrorMessage) -> existingErrorMessage + ", " + newErrorMessage); + }); + + return handleExceptionInternalArgs(e,HttpHeaders.EMPTY,ErrorStatus.valueOf("_BAD_REQUEST"),request,errors); + } + + @ExceptionHandler + public ResponseEntity exception(Exception e, WebRequest request) { + e.printStackTrace(); + + return handleExceptionInternalFalse(e, ErrorStatus._INTERNAL_SERVER_ERROR, HttpHeaders.EMPTY, ErrorStatus._INTERNAL_SERVER_ERROR.getHttpStatus(),request, e.getMessage()); + } + + @ExceptionHandler(value = GeneralException.class) + public ResponseEntity onThrowException(GeneralException generalException, HttpServletRequest request) { + ErrorReasonDTO errorReasonHttpStatus = generalException.getErrorReasonHttpStatus(); + return handleExceptionInternal(generalException,errorReasonHttpStatus,null,request); + } + + @ExceptionHandler(RegionNotFoundException.class) + public ResponseEntity handleRegionNotFound(RegionNotFoundException ex, WebRequest request) { + return handleExceptionInternal( + ex, + ErrorStatus.valueOf("_BAD_REQUEST").getReasonHttpStatus(), + new HttpHeaders(), + ((ServletWebRequest) request).getRequest()); + } + + // 추가 + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException e) { + return ResponseEntity.badRequest().body(ApiResponse.onFailure("400", e.getMessage(), null)); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity> handleIllegalStateException(IllegalStateException ex) { + ApiResponse response = ApiResponse.onFailure("ALREADY_INACTIVE", ex.getMessage(), null); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + + private ResponseEntity handleExceptionInternal(Exception e, ErrorReasonDTO reason, + HttpHeaders headers, HttpServletRequest request) { + + ApiResponse body = ApiResponse.onFailure(reason.getCode(),reason.getMessage(),null); +// e.printStackTrace(); + + WebRequest webRequest = new ServletWebRequest(request); + return super.handleExceptionInternal( + e, + body, + headers, + reason.getHttpStatus(), + webRequest + ); + } + + private ResponseEntity handleExceptionInternalFalse(Exception e, ErrorStatus errorCommonStatus, + HttpHeaders headers, HttpStatus status, WebRequest request, String errorPoint) { + ApiResponse body = ApiResponse.onFailure(errorCommonStatus.getCode(),errorCommonStatus.getMessage(),errorPoint); + return super.handleExceptionInternal( + e, + body, + headers, + status, + request + ); + } + + private ResponseEntity handleExceptionInternalArgs(Exception e, HttpHeaders headers, ErrorStatus errorCommonStatus, + WebRequest request, Map errorArgs) { + ApiResponse body = ApiResponse.onFailure(errorCommonStatus.getCode(),errorCommonStatus.getMessage(),errorArgs); + return super.handleExceptionInternal( + e, + body, + headers, + errorCommonStatus.getHttpStatus(), + request + ); + } + + private ResponseEntity handleExceptionInternalConstraint(Exception e, ErrorStatus errorCommonStatus, + HttpHeaders headers, WebRequest request) { + ApiResponse body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), null); + return super.handleExceptionInternal( + e, + body, + headers, + errorCommonStatus.getHttpStatus(), + request + ); + } +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/exception/GeneralException.java b/week5/spring/src/main/java/umc/study/apiPayload/exception/GeneralException.java new file mode 100644 index 0000000..e9a456e --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/exception/GeneralException.java @@ -0,0 +1,21 @@ +package umc.study.apiPayload.exception; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import umc.study.apiPayload.code.BaseErrorCode; +import umc.study.apiPayload.code.ErrorReasonDTO; + +@Getter +@AllArgsConstructor +public class GeneralException extends RuntimeException { + + private BaseErrorCode code; + + public ErrorReasonDTO getErrorReason() { + return this.code.getReason(); + } + + public ErrorReasonDTO getErrorReasonHttpStatus(){ + return this.code.getReasonHttpStatus(); + } +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/exception/RegionNotFoundException.java b/week5/spring/src/main/java/umc/study/apiPayload/exception/RegionNotFoundException.java new file mode 100644 index 0000000..c77816c --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/exception/RegionNotFoundException.java @@ -0,0 +1,19 @@ +package umc.study.apiPayload.exception; + +import umc.study.apiPayload.code.BaseErrorCode; +import umc.study.apiPayload.code.ErrorReasonDTO; +import umc.study.apiPayload.code.status.ErrorStatus; + +public class RegionNotFoundException extends GeneralException { + + public RegionNotFoundException() { + super( + (BaseErrorCode) ErrorReasonDTO.builder() + .httpStatus(ErrorStatus._BAD_REQUEST.getHttpStatus()) + .isSuccess(false) + .code(ErrorStatus._BAD_REQUEST.getCode()) + .message("Region not found.") + .build() + ); + } +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/exception/handler/FoodHandler.java b/week5/spring/src/main/java/umc/study/apiPayload/exception/handler/FoodHandler.java new file mode 100644 index 0000000..61fbf24 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/exception/handler/FoodHandler.java @@ -0,0 +1,11 @@ +package umc.study.apiPayload.exception.handler; + +import umc.study.apiPayload.code.BaseErrorCode; +import umc.study.apiPayload.exception.GeneralException; + +public class FoodHandler extends GeneralException { + + public FoodHandler(BaseErrorCode errorCode) { + super(errorCode); + } +} diff --git a/week5/spring/src/main/java/umc/study/apiPayload/exception/handler/TempHandler.java b/week5/spring/src/main/java/umc/study/apiPayload/exception/handler/TempHandler.java new file mode 100644 index 0000000..5ca4a8f --- /dev/null +++ b/week5/spring/src/main/java/umc/study/apiPayload/exception/handler/TempHandler.java @@ -0,0 +1,11 @@ +package umc.study.apiPayload.exception.handler; + +import umc.study.apiPayload.code.BaseErrorCode; +import umc.study.apiPayload.exception.GeneralException; + +public class TempHandler extends GeneralException { + + public TempHandler(BaseErrorCode errorCode) { + super(errorCode); + } +} diff --git a/week5/spring/src/main/java/umc/study/config/QueryDSLConfig.java b/week5/spring/src/main/java/umc/study/config/QueryDSLConfig.java new file mode 100644 index 0000000..be49540 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/config/QueryDSLConfig.java @@ -0,0 +1,18 @@ +package umc.study.config; + +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@RequiredArgsConstructor +public class QueryDSLConfig { + private final EntityManager entityManager; + + @Bean + public JPAQueryFactory jpaQueryFactory(){ + return new JPAQueryFactory(entityManager); + } +} diff --git a/week5/spring/src/main/java/umc/study/config/SwaggerConfig.java b/week5/spring/src/main/java/umc/study/config/SwaggerConfig.java new file mode 100644 index 0000000..e2b25ab --- /dev/null +++ b/week5/spring/src/main/java/umc/study/config/SwaggerConfig.java @@ -0,0 +1,40 @@ +package umc.study.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 UMCstudyAPI() { + Info info = new Info() + .title("UMC Server WorkBook API") + .description("UMC Server WorkBook API 명세서") + .version("1.0.0"); + + String jwtSchemeName = "JWT TOKEN"; + // API 요청헤더에 인증정보 포함 + SecurityRequirement securityRequirement = new SecurityRequirement().addList(jwtSchemeName); + // SecuritySchemes 등록 + Components components = new Components() + .addSecuritySchemes(jwtSchemeName, new SecurityScheme() + .name(jwtSchemeName) + .type(SecurityScheme.Type.HTTP) // HTTP 방식 + .scheme("bearer") + .bearerFormat("JWT")); + + return new OpenAPI() + .addServersItem(new Server().url("/")) + .info(info) + .addSecurityItem(securityRequirement) + .components(components); + } +} diff --git a/week5/spring/src/main/java/umc/study/converter/MissionConverter.java b/week5/spring/src/main/java/umc/study/converter/MissionConverter.java new file mode 100644 index 0000000..69e33a6 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/converter/MissionConverter.java @@ -0,0 +1,36 @@ +package umc.study.converter; + +import org.springframework.stereotype.Component; +import umc.study.domain.Mission; +import umc.study.domain.Store; +import umc.study.web.dto.MissionRequestDTO; +import umc.study.web.dto.MissionResponseDTO; + +import java.time.LocalDateTime; + +@Component +public class MissionConverter { + + public static Mission toEntity(MissionRequestDTO requestDTO, Store store) { + return Mission.builder() + .store(store) + .missionDescription(requestDTO.getMissionDescription()) + .missionPoint(requestDTO.getMissionPoint()) + .deadline(requestDTO.getDeadline()) + .build(); + } + + public static MissionResponseDTO toResponseDTO(Mission mission) { + return MissionResponseDTO.builder() + .id(mission.getId()) + .storeId(mission.getStore().getId()) +// .storeName(mission.getStore().getStoreName()) + .missionDescription(mission.getMissionDescription()) + .missionPoint(mission.getMissionPoint()) + .deadline(mission.getDeadline()) + .status(mission.getStatus().name()) + .createdAt(mission.getCreatedAt()) + .updatedAt(mission.getUpdatedAt()) + .build(); + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/converter/ReviewConverter.java b/week5/spring/src/main/java/umc/study/converter/ReviewConverter.java new file mode 100644 index 0000000..26ecf13 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/converter/ReviewConverter.java @@ -0,0 +1,32 @@ +package umc.study.converter; + +import umc.study.domain.Review; +import umc.study.domain.Store; +import umc.study.domain.User; +import umc.study.web.dto.ReviewRequestDTO; +import umc.study.web.dto.ReviewResponseDTO; + +public class ReviewConverter { + + public static Review toEntity(ReviewRequestDTO request, User user, Store store) { + return Review.builder() + .user(user) + .store(store) + .reviewContent(request.getReviewContent()) + .reviewImg(request.getReviewImg()) + .reviewScope(request.getReviewScope()) + .build(); + } + + public static ReviewResponseDTO toResponseDTO(Review review) { + return ReviewResponseDTO.builder() + .id(review.getId()) + .storeId(review.getStore().getId()) + .userId(review.getUser().getId()) + .reviewContent(review.getReviewContent()) + .reviewImg(review.getReviewImg()) + .reviewScope(review.getReviewScope().name()) + .createdAt(review.getCreatedAt()) + .build(); + } +} diff --git a/week5/spring/src/main/java/umc/study/converter/StoreConverter.java b/week5/spring/src/main/java/umc/study/converter/StoreConverter.java new file mode 100644 index 0000000..5da1429 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/converter/StoreConverter.java @@ -0,0 +1,35 @@ +package umc.study.converter; + +import umc.study.domain.Food; +import umc.study.domain.Region; +import umc.study.domain.Store; +import umc.study.web.dto.StoreRequestDTO; +import umc.study.web.dto.StoreResponseDTO; + +import java.math.BigDecimal; + +public class StoreConverter { + + public static Store toEntity(StoreRequestDTO request, Region region, Food food) { + return Store.builder() + .storeName(request.getStoreName()) + .address(request.getAddress()) + .status(request.getStatus()) + .storeScope(BigDecimal.ZERO) + .region(region) + .food(food) // food 설정 + .build(); + } + + public static StoreResponseDTO toResponseDTO(Store store) { + return StoreResponseDTO.builder() + .id(store.getId()) + .storeName(store.getStoreName()) + .address(store.getAddress()) + .status(store.getStatus()) + .storeScope(store.getStoreScope()) + .regionId(store.getRegion().getId()) + .id(store.getFood().getId()) // food_id 포함 + .build(); + } +} diff --git a/week5/spring/src/main/java/umc/study/converter/TempConverter.java b/week5/spring/src/main/java/umc/study/converter/TempConverter.java new file mode 100644 index 0000000..7654c4d --- /dev/null +++ b/week5/spring/src/main/java/umc/study/converter/TempConverter.java @@ -0,0 +1,18 @@ +package umc.study.converter; + +import umc.study.web.dto.TempResponse; + +public class TempConverter { + + public static TempResponse.TempTestDTO toTempTestDTO(){ + return TempResponse.TempTestDTO.builder() + .testString("This is Test!") + .build(); + } + + public static TempResponse.TempExceptionDTO toTempExceptionDTO(Integer flag){ + return TempResponse.TempExceptionDTO.builder() + .flag(flag) + .build(); + } +} diff --git a/week5/spring/src/main/java/umc/study/converter/UserConverter.java b/week5/spring/src/main/java/umc/study/converter/UserConverter.java new file mode 100644 index 0000000..bf44984 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/converter/UserConverter.java @@ -0,0 +1,42 @@ +package umc.study.converter; + +import umc.study.domain.User; +import umc.study.domain.enums.Gender; +import umc.study.web.dto.UserRequestDTO; +import umc.study.web.dto.UserResponseDTO; + +import java.time.LocalDateTime; +import java.util.ArrayList; + +public class UserConverter { + public static UserResponseDTO.JoinResultDTO toJoinResultDTO(User user){ + return UserResponseDTO.JoinResultDTO.builder() + .userId(user.getId()) + .createdAt(LocalDateTime.now()) + .build(); + } + +// public static User toUser(UserRequestDTO.JoinDto request){ +// return User.builder() +// .userAddress(request.getUserAddress()) +// .gender(Gender.fromCode(request.getGender())) // Enum 변환 +// .user_name(request.getName()) +// .userBirth(request.getUserBirth()) +// .userFavoriteFoodsList(new ArrayList<>()) +// .build(); +// } + public static User toUser(UserRequestDTO.JoinDto request) { + Gender gender = Gender.fromString(request.getGender()); // Gender 변환 + + return User.builder() + .userAddress(request.getUserAddress()) + .gender(gender) + .userName(request.getName()) + .userBirth(request.getUserBirth()) // 생일 추가 매핑 + .userFavoriteFoodsList(new ArrayList<>()) + .build(); + } + + +} + diff --git a/week5/spring/src/main/java/umc/study/converter/UserFavoriteFoodConverter.java b/week5/spring/src/main/java/umc/study/converter/UserFavoriteFoodConverter.java new file mode 100644 index 0000000..85a54a3 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/converter/UserFavoriteFoodConverter.java @@ -0,0 +1,19 @@ +package umc.study.converter; + +import umc.study.domain.Food; +import umc.study.domain.UserFavoriteFoods; + +import java.util.List; +import java.util.stream.Collectors; + +public class UserFavoriteFoodConverter { + public static List toUserFavoriteFoodsList(List foodList){ + + return foodList.stream() + .map(food -> + UserFavoriteFoods.builder() + .food(food) + .build() + ).collect(Collectors.toList()); + } +} diff --git a/week5/spring/src/main/java/umc/study/domain/Food.java b/week5/spring/src/main/java/umc/study/domain/Food.java new file mode 100644 index 0000000..7da82a9 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/Food.java @@ -0,0 +1,31 @@ +package umc.study.domain; + +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Food { + + // 음식의 종류는 정해져 있음 -> AUTO_INCREMENT 사용 X + @Id + @Column(nullable = false) + private Long id; + + @Column(nullable = false, length = 50, unique = true) + private String foodName; + + @OneToMany(mappedBy = "food",cascade=CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List storeList = new ArrayList<>(); + + @OneToMany(mappedBy = "food",cascade=CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List userFavoriteFoodsList = new ArrayList<>(); +} diff --git a/week5/spring/src/main/java/umc/study/domain/Mission.java b/week5/spring/src/main/java/umc/study/domain/Mission.java new file mode 100644 index 0000000..315c3e8 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/Mission.java @@ -0,0 +1,89 @@ +package umc.study.domain; + +import jakarta.persistence.*; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.*; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import umc.study.domain.enums.Status; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@EntityListeners(AuditingEntityListener.class) +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Mission { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(nullable = false) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + @NotBlank + @Size(min = 5, max = 255) + @Column(nullable = false) + private String missionDescription; + + @NotNull + @Column(nullable = false) + private Integer missionPoint; + + @NotNull + @Column(nullable = false) + private LocalDateTime deadline; + + private LocalDate inactiveDate; + + @Enumerated(EnumType.STRING) + @Builder.Default + private Status status = Status.ACTIVE; + + @CreatedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime updatedAt; + + @OneToMany(mappedBy = "mission",cascade=CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List userMissionList = new ArrayList<>(); + + public void setStatus(Status status) { + this.status = status; + } + + public void setStore(Store store) { + if (this.store != null && this.store.getMissionList() != null) { + this.store.getMissionList().remove(this); + } + this.store = store; + if (store != null && !store.getMissionList().contains(this)) { + store.getMissionList().add(this); + } + } + + // 데이터 무결성 검증 + public void validate() { + if (missionPoint == null || missionPoint <= 0) { + throw new IllegalArgumentException("미션 보상 포인트는 반드시 0 포인트 이상이어야 합니다."); + } + if (deadline == null || deadline.isBefore(LocalDateTime.now())) { + throw new IllegalArgumentException("Deadline은 반드시 미래의 시간대여야 합니다."); + } + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/domain/Region.java b/week5/spring/src/main/java/umc/study/domain/Region.java new file mode 100644 index 0000000..d31b937 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/Region.java @@ -0,0 +1,51 @@ +package umc.study.domain; + +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.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@EntityListeners(AuditingEntityListener.class) +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Region { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(nullable = false) + private Long id; + + @Column(nullable = false, length = 20, unique = true) + private String name; + + @CreatedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime updatedAt; + + @OneToMany(mappedBy = "region",cascade=CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List storeList = new ArrayList<>(); + + public void addStore(Store store) { + storeList.add(store); + store.setRegion(this); + } + + public void removeStore(Store store) { + storeList.remove(store); + store.setRegion(null); + } +} + diff --git a/week5/spring/src/main/java/umc/study/domain/Review.java b/week5/spring/src/main/java/umc/study/domain/Review.java new file mode 100644 index 0000000..8e888f1 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/Review.java @@ -0,0 +1,71 @@ +package umc.study.domain; + +import jakarta.persistence.*; +import jakarta.validation.constraints.Size; +import lombok.*; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import umc.study.domain.enums.ReviewScope; + +import java.time.LocalDateTime; + +@Entity +@EntityListeners(AuditingEntityListener.class) +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Review { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(nullable = false) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; + + private String reviewImg; + + @Column(length = 500) + @Size(max = 500, message = "Review content must be 500 characters or less.") + private String reviewContent; + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private ReviewScope reviewScope; + + @CreatedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime updatedAt; + + public void setStore(Store store) { + if (this.store != null && this.store.getReviewList() != null) { + this.store.getReviewList().remove(this); + } + this.store = store; + if (store != null && !store.getReviewList().contains(this)) { + store.getReviewList().add(this); + } + } + + public void setUser(User user) { + if (this.user != null && this.user.getReviewList() != null) { + this.user.getReviewList().remove(this); + } + this.user = user; + if (user != null && !user.getReviewList().contains(this)) { + user.getReviewList().add(this); + } + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/domain/Store.java b/week5/spring/src/main/java/umc/study/domain/Store.java new file mode 100644 index 0000000..6ccce9c --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/Store.java @@ -0,0 +1,118 @@ +package umc.study.domain; + +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 umc.study.domain.enums.Status; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + + +@Entity +@EntityListeners(AuditingEntityListener.class) +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Store { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) // Auto_Increment + 인덱스 유지(앞의 인덱스가 삭제되어도) + @Column(nullable = false) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "food_id") + private Food food; + + @Column(nullable = false) + private String address; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "region_id") + private Region region; + + @Column(nullable = false, length = 50) + private String storeName; + + @Column(precision = 10, scale = 2, columnDefinition = "DECIMAL(10, 2) DEFAULT 0.00") + private BigDecimal storeScope = BigDecimal.ZERO; + + @CreatedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime updatedAt; + + private LocalDate inactiveDate; + + @Enumerated(EnumType.STRING) + private Status status = Status.ACTIVE; + + @OneToMany(mappedBy = "store",cascade=CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List missionList = new ArrayList<>(); + + @OneToMany(mappedBy = "store",cascade=CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List reviewList = new ArrayList<>(); + + // 리뷰들의 평균값을 계산하여 storeScope를 업데이트하는 메서드 + public void updateStoreScope() { + if (reviewList.isEmpty()) { + this.storeScope = BigDecimal.ZERO; + return; + } + + BigDecimal total = reviewList.stream() + .map(review -> new BigDecimal(review.getReviewScope().getValue())) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + BigDecimal average = total.divide(new BigDecimal(reviewList.size()), 2, RoundingMode.HALF_UP); + this.storeScope = average; + } + + // 리뷰 추가 메서드 + public void addReview(Review review) { + reviewList.add(review); + review.setStore(this); + } + + // 리뷰 삭제 메서드 + public void removeReview(Review review) { + reviewList.remove(review); + review.setStore(null); + } + + // 미션 추가 메서드 + public void addMission(Mission mission) { + missionList.add(mission); + mission.setStore(this); + } + + // 미션 삭제 메서드 + public void removeMission(Mission mission) { + missionList.remove(mission); + mission.setStore(null); + } + + // 지역 설정 메서드 + public void setRegion(Region region) { + if (this.region != null) { + this.region.getStoreList().remove(this); + } + this.region = region; + if (!region.getStoreList().contains(this)) { + region.getStoreList().add(this); + } + } +} diff --git a/week5/spring/src/main/java/umc/study/domain/User.java b/week5/spring/src/main/java/umc/study/domain/User.java new file mode 100644 index 0000000..42f68fe --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/User.java @@ -0,0 +1,80 @@ +package umc.study.domain; + +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.DynamicInsert; +import org.hibernate.annotations.DynamicUpdate; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import umc.study.domain.enums.Gender; +import umc.study.domain.enums.Status; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@EntityListeners(AuditingEntityListener.class) +@Getter +@DynamicUpdate +@DynamicInsert +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(nullable = false) + private Long id; + + @Column(nullable = false, length = 20) + private String userName; + + @Enumerated(EnumType.STRING) + @Column(nullable = false) // Gender는 필수값으로 처리 + private Gender gender; + + @Column(nullable = false) + private LocalDate userBirth; + + private String userAddress; + + @Builder.Default + private Boolean userLogin = false; + + @Builder.Default + private Integer userPoint = 0; + + @Enumerated(EnumType.STRING) + private Status status = Status.ACTIVE; + + private LocalDate inactive_date; + + @Column(unique = true) + private String userEmail; + + @Column(unique = true) + private String userPhone; + + @CreatedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(nullable = false, columnDefinition = "DATETIME(6)") + private LocalDateTime updatedAt; + + @OneToMany(mappedBy = "user",cascade=CascadeType.ALL, orphanRemoval = true) + private List reviewList = new ArrayList<>(); + + @OneToMany(mappedBy = "user",cascade=CascadeType.ALL, orphanRemoval = true) + private List userMissionList = new ArrayList<>(); + + @OneToMany(mappedBy = "user",cascade=CascadeType.ALL, orphanRemoval = true) + private List userFavoriteFoodsList = new ArrayList<>(); +} + + diff --git a/week5/spring/src/main/java/umc/study/domain/UserFavoriteFoods.java b/week5/spring/src/main/java/umc/study/domain/UserFavoriteFoods.java new file mode 100644 index 0000000..10932aa --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/UserFavoriteFoods.java @@ -0,0 +1,59 @@ +package umc.study.domain; + +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class UserFavoriteFoods { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(nullable = false) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "food_id") + private Food food; + + + public void setUser(User user) { + updateUserRelationship(user); + } + + public void setFood(Food food) { + updateFoodRelationship(food); + } + + private void updateUserRelationship(User newUser) { + // 기존 관계 해제 + if (this.user != null) { + this.user.getUserFavoriteFoodsList().remove(this); + } + // 새 관계 설정 + this.user = newUser; + if (newUser != null) { + newUser.getUserFavoriteFoodsList().add(this); + } + } + + private void updateFoodRelationship(Food newFood) { + // 기존 관계 해제 + if (this.food != null) { + this.food.getUserFavoriteFoodsList().remove(this); + } + // 새 관계 설정 + this.food = newFood; + if (newFood != null) { + newFood.getUserFavoriteFoodsList().add(this); + } + } + +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/domain/UserMission.java b/week5/spring/src/main/java/umc/study/domain/UserMission.java new file mode 100644 index 0000000..0283d39 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/UserMission.java @@ -0,0 +1,57 @@ +package umc.study.domain; + +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class UserMission { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(nullable = false) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "mission_id") + private Mission mission; + + public void setUser(User user) { + if (this.user != null) { + this.user.getUserMissionList().remove(this); + } + this.user = user; + if (user != null && !user.getUserMissionList().contains(this)) { + user.getUserMissionList().add(this); + } + } + + public void setMission(Mission mission) { + if (this.mission != null) { + this.mission.getUserMissionList().remove(this); + } + this.mission = mission; + if (mission != null && !mission.getUserMissionList().contains(this)) { + mission.getUserMissionList().add(this); + } + } + + // 유효성 검증 메서드 + public void validate() { + if (user == null) { + throw new IllegalArgumentException("유저가 있어야 합니다."); + } + if (mission == null) { + throw new IllegalArgumentException("미션이 있어야 합니다."); + } + } + + +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/domain/enums/Gender.java b/week5/spring/src/main/java/umc/study/domain/enums/Gender.java new file mode 100644 index 0000000..3da3a32 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/enums/Gender.java @@ -0,0 +1,16 @@ +package umc.study.domain.enums; + +import java.util.Arrays; + +public enum Gender { + Male, Female, None; + + public static Gender fromString(String value) { + try { + return Gender.valueOf(value); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("잘못된 형식으로 입력 : (Male, Female, None)" + value); + } + } +} + diff --git a/week5/spring/src/main/java/umc/study/domain/enums/ReviewScope.java b/week5/spring/src/main/java/umc/study/domain/enums/ReviewScope.java new file mode 100644 index 0000000..322c129 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/enums/ReviewScope.java @@ -0,0 +1,29 @@ +package umc.study.domain.enums; + +import java.util.Arrays; + +public enum ReviewScope { + ONE(1), + TWO(2), + THREE(3), + FOUR(4), + FIVE(5); + + private final int value; + + ReviewScope(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + // 정수 값을 기반으로 ReviewScope를 반환하는 메서드 + public static ReviewScope fromValue(int value) { + return Arrays.stream(values()) + .filter(scope -> scope.value == value) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("잘못된 형식으로 입력 : (1, 2, 3, 4, 5)" + value)); + } +} diff --git a/week5/spring/src/main/java/umc/study/domain/enums/Status.java b/week5/spring/src/main/java/umc/study/domain/enums/Status.java new file mode 100644 index 0000000..5a8d710 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/domain/enums/Status.java @@ -0,0 +1,16 @@ +package umc.study.domain.enums; + +public enum Status { + ACTIVE, INACTIVE; + + public static Status fromString(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Status는 절대 비거나 NULL이면 앙댐"); + } + try { + return Status.valueOf(value.trim().toUpperCase()); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("잘못된 형식으로 입력 : " + value + ". (ACTIVE, INACTIVE)"); + } + } +} diff --git a/week5/spring/src/main/java/umc/study/repository/MissionRepository/MissionRepository.java b/week5/spring/src/main/java/umc/study/repository/MissionRepository/MissionRepository.java new file mode 100644 index 0000000..c584ba6 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/MissionRepository/MissionRepository.java @@ -0,0 +1,14 @@ +package umc.study.repository.MissionRepository; + +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 umc.study.domain.Mission; +import umc.study.domain.UserMission; +import umc.study.domain.enums.Status; + +public interface MissionRepository extends JpaRepository { + Page findAllByStoreId(Long storeId, Pageable pageable); +} diff --git a/week5/spring/src/main/java/umc/study/repository/RegionRepository/RegionRepository.java b/week5/spring/src/main/java/umc/study/repository/RegionRepository/RegionRepository.java new file mode 100644 index 0000000..6d64b6f --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/RegionRepository/RegionRepository.java @@ -0,0 +1,7 @@ +package umc.study.repository.RegionRepository; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.study.domain.Region; + +public interface RegionRepository extends JpaRepository { +} diff --git a/week5/spring/src/main/java/umc/study/repository/ReviewRepository/ReviewRepository.java b/week5/spring/src/main/java/umc/study/repository/ReviewRepository/ReviewRepository.java new file mode 100644 index 0000000..d966eb8 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/ReviewRepository/ReviewRepository.java @@ -0,0 +1,10 @@ +package umc.study.repository.ReviewRepository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import umc.study.domain.Review; + +public interface ReviewRepository extends JpaRepository { + Page findAllByUserId(Long userId, Pageable pageable); +} diff --git a/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepository.java b/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepository.java new file mode 100644 index 0000000..4383484 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepository.java @@ -0,0 +1,10 @@ +package umc.study.repository.StoreRepository; + +import umc.study.domain.Store; +import org.springframework.data.jpa.repository.JpaRepository; +import umc.study.repository.StoreRepository.StoreRepositoryCustom; + +// 이 놈은 StoreRepository의 근본 +public interface StoreRepository extends JpaRepository, StoreRepositoryCustom { + boolean existsById(Long id); // 추가 +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepositoryCustom.java b/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepositoryCustom.java new file mode 100644 index 0000000..d268870 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepositoryCustom.java @@ -0,0 +1,10 @@ +package umc.study.repository.StoreRepository; + +import umc.study.domain.Store; + +import java.util.List; + +// 이 놈은 QueryDSL을 사용하여 사용자 정의 쿼리를 작성할 수 있는 메서드를 정의하는 놈 +public interface StoreRepositoryCustom { + List dynamicQueryWithBooleanBuilder(String name, Float score); +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepositoryImpl.java b/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepositoryImpl.java new file mode 100644 index 0000000..a346303 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/StoreRepository/StoreRepositoryImpl.java @@ -0,0 +1,36 @@ +package umc.study.repository.StoreRepository; + +import com.querydsl.core.BooleanBuilder; +import com.querydsl.jpa.impl.JPAQueryFactory; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import umc.study.domain.QStore; +import umc.study.domain.Store; + +import java.util.List; + +// 이 놈이 실질적인 QueryDSL에서 필터링 조건을 담은 , 즉 동적 쿼리 본체 +@Repository +@RequiredArgsConstructor +public class StoreRepositoryImpl implements StoreRepositoryCustom{ + private final JPAQueryFactory jpaQueryFactory; + private final QStore store = QStore.store; + + @Override + public List dynamicQueryWithBooleanBuilder(String name, Float score) { + BooleanBuilder predicate = new BooleanBuilder(); + + if (name != null) { + predicate.and(store.storeName.eq(name)); + } + + if (score != null) { + predicate.and(store.storeScope.goe(4.0f)); + } + + return jpaQueryFactory + .selectFrom(store) + .where(predicate) + .fetch(); + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/repository/UserMissionRepository/UserMissionRepository.java b/week5/spring/src/main/java/umc/study/repository/UserMissionRepository/UserMissionRepository.java new file mode 100644 index 0000000..a872692 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/UserMissionRepository/UserMissionRepository.java @@ -0,0 +1,15 @@ +package umc.study.repository.UserMissionRepository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import umc.study.domain.UserMission; +import umc.study.domain.enums.Status; + +public interface UserMissionRepository extends JpaRepository { + boolean existsByUserIdAndMissionId(Long userId, Long missionId); + Page findAllByUserId(Long userId, Pageable pageable); + + Page findByUserIdAndMissionStatus(Long userId, Status status, Pageable pageable); + +} diff --git a/week5/spring/src/main/java/umc/study/repository/UserRepository/FoodRepository.java b/week5/spring/src/main/java/umc/study/repository/UserRepository/FoodRepository.java new file mode 100644 index 0000000..ba3f02d --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/UserRepository/FoodRepository.java @@ -0,0 +1,8 @@ +package umc.study.repository.UserRepository; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.study.domain.Food; + +// 이게 Long이 맞나? +public interface FoodRepository extends JpaRepository { +} diff --git a/week5/spring/src/main/java/umc/study/repository/UserRepository/UserRepository.java b/week5/spring/src/main/java/umc/study/repository/UserRepository/UserRepository.java new file mode 100644 index 0000000..399a5aa --- /dev/null +++ b/week5/spring/src/main/java/umc/study/repository/UserRepository/UserRepository.java @@ -0,0 +1,7 @@ +package umc.study.repository.UserRepository; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.study.domain.User; + +public interface UserRepository extends JpaRepository { +} diff --git a/week5/spring/src/main/java/umc/study/service/MissionService/MissionService.java b/week5/spring/src/main/java/umc/study/service/MissionService/MissionService.java new file mode 100644 index 0000000..8167138 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/MissionService/MissionService.java @@ -0,0 +1,58 @@ +package umc.study.service.MissionService; + +import umc.study.domain.enums.Status; +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 umc.study.converter.MissionConverter; +import umc.study.domain.Mission; +import umc.study.domain.Store; +import umc.study.repository.MissionRepository.MissionRepository; +import umc.study.repository.StoreRepository.StoreRepository; +import umc.study.web.dto.MissionRequestDTO; +import umc.study.web.dto.MissionResponseDTO; + +@Service +@RequiredArgsConstructor +public class MissionService { + + private final MissionRepository missionRepository; + private final StoreRepository storeRepository; + + @Transactional + public MissionResponseDTO addMission(MissionRequestDTO requestDTO) { + Store store = storeRepository.findById(requestDTO.getStoreId()) + .orElseThrow(() -> new IllegalArgumentException("가게 찾을 수 없음")); + + Mission mission = Mission.builder() + .store(store) + .missionDescription(requestDTO.getMissionDescription()) + .missionPoint(requestDTO.getMissionPoint()) + .deadline(requestDTO.getDeadline()) + .build(); + + missionRepository.save(mission); + return MissionConverter.toResponseDTO(mission); + } + + public Page getMissionsByStore(Long storeId, Pageable pageable) { + Page missions = missionRepository.findAllByStoreId(storeId, pageable); + return missions.map(MissionConverter::toResponseDTO); + } + + @Transactional + public void updateMissionStatus(Long missionId) { + Mission mission = missionRepository.findById(missionId) + .orElseThrow(() -> new IllegalArgumentException("미션을 찾을 수 없습니다.")); + + // 상태가 이미 INACTIVE인지 검증 + if (mission.getStatus() == Status.INACTIVE) { + throw new IllegalStateException("이미 INACTIVE 상태인 미션입니다."); + } + + // 상태를 INACTIVE로 변경 + mission.setStatus(Status.INACTIVE); + } +} diff --git a/week5/spring/src/main/java/umc/study/service/RegionService/RegionService.java b/week5/spring/src/main/java/umc/study/service/RegionService/RegionService.java new file mode 100644 index 0000000..58d5ae1 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/RegionService/RegionService.java @@ -0,0 +1,38 @@ +package umc.study.service.RegionService; + +import umc.study.apiPayload.exception.RegionNotFoundException; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import umc.study.converter.StoreConverter; +import umc.study.domain.Food; +import umc.study.domain.Region; +import umc.study.domain.Store; +import umc.study.repository.RegionRepository.RegionRepository; +import umc.study.repository.StoreRepository.StoreRepository; +import umc.study.repository.UserRepository.FoodRepository; +import umc.study.web.dto.StoreRequestDTO; +import umc.study.web.dto.StoreResponseDTO; + +@Service +@RequiredArgsConstructor +public class RegionService { + + private final RegionRepository regionRepository; + private final StoreRepository storeRepository; + private final FoodRepository foodRepository; + + @Transactional + public StoreResponseDTO addStoreToRegion(Long regionId, StoreRequestDTO storeRequestDTO) { + Region region = regionRepository.findById(regionId) + .orElseThrow(RegionNotFoundException::new); + + Food food = foodRepository.findById(storeRequestDTO.getFoodId()) + .orElseThrow(() -> new IllegalArgumentException("ID로 음식을 찾을 수 없음 : " + storeRequestDTO.getFoodId())); + + Store store = StoreConverter.toEntity(storeRequestDTO, region, food); + storeRepository.save(store); + + return StoreConverter.toResponseDTO(store); + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/service/ReviewService/ReviewService.java b/week5/spring/src/main/java/umc/study/service/ReviewService/ReviewService.java new file mode 100644 index 0000000..39b1e2c --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/ReviewService/ReviewService.java @@ -0,0 +1,49 @@ +package umc.study.service.ReviewService; + +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 umc.study.converter.ReviewConverter; +import umc.study.domain.Review; +import umc.study.domain.Store; +import umc.study.domain.User; +import umc.study.repository.ReviewRepository.ReviewRepository; +import umc.study.repository.StoreRepository.StoreRepository; +import umc.study.repository.UserRepository.UserRepository; +import umc.study.web.dto.ReviewRequestDTO; +import umc.study.web.dto.ReviewResponseDTO; + +@Service +@RequiredArgsConstructor +public class ReviewService { + + private final ReviewRepository reviewRepository; + private final StoreRepository storeRepository; + private final UserRepository userRepository; + + @Transactional + public ReviewResponseDTO addReviewToStore(ReviewRequestDTO request) { + // storeId는 DTO에서 검증되므로 다시 확인할 필요 없음 + Store store = storeRepository.findById(request.getStoreId()) + .orElseThrow(() -> new IllegalArgumentException("ID와 함께 가게를 찾지 못함 : " + request.getStoreId())); + + User user = userRepository.findById(request.getUserId()) + .orElseThrow(() -> new IllegalArgumentException("ID와 함께 유저를 찾지 못함 : " + request.getUserId())); + + Review review = ReviewConverter.toEntity(request, user, store); + store.addReview(review); // 양방향 관계 설정 + reviewRepository.save(review); + + // Store의 리뷰 평균 스코프 업데이트 + store.updateStoreScope(); + + return ReviewConverter.toResponseDTO(review); + } + + public Page getMyReviews(Pageable pageable) { + return reviewRepository.findAllByUserId(1L, pageable) // 동동(user_id=1) 기준 + .map(ReviewConverter::toResponseDTO); + } +} diff --git a/week5/spring/src/main/java/umc/study/service/StoreService/StoreQueryService.java b/week5/spring/src/main/java/umc/study/service/StoreService/StoreQueryService.java new file mode 100644 index 0000000..eb49429 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/StoreService/StoreQueryService.java @@ -0,0 +1,12 @@ +package umc.study.service.StoreService; + +import umc.study.domain.Store; + +import java.util.List; +import java.util.Optional; + +public interface StoreQueryService { + + Optional findStore(Long id); + List findStoresByNameAndScore(String name, Float score); +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/service/StoreService/StoreQueryServiceImpl.java b/week5/spring/src/main/java/umc/study/service/StoreService/StoreQueryServiceImpl.java new file mode 100644 index 0000000..e8aca1c --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/StoreService/StoreQueryServiceImpl.java @@ -0,0 +1,33 @@ +package umc.study.service.StoreService; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import umc.study.domain.Store; +import umc.study.repository.StoreRepository.StoreRepository; + +import java.util.List; +import java.util.Optional; + +// 이제 여기서 실제로 StoreRepository를 사용해 정의한 메서드를 구현하는 거 즉, 실행! +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class StoreQueryServiceImpl implements StoreQueryService{ + + private final StoreRepository storeRepository; + + @Override + public Optional findStore(Long id) { + return storeRepository.findById(id); + } + + @Override + public List findStoresByNameAndScore(String name, Float score) { + List filteredStores = storeRepository.dynamicQueryWithBooleanBuilder(name, score); + + filteredStores.forEach(store -> System.out.println("Store: " + store)); + + return filteredStores; + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/service/TempService/TempCommandService.java b/week5/spring/src/main/java/umc/study/service/TempService/TempCommandService.java new file mode 100644 index 0000000..c21d1aa --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/TempService/TempCommandService.java @@ -0,0 +1,4 @@ +package umc.study.service.TempService; + +public interface TempCommandService { +} diff --git a/week5/spring/src/main/java/umc/study/service/TempService/TempCommandServiceImpl.java b/week5/spring/src/main/java/umc/study/service/TempService/TempCommandServiceImpl.java new file mode 100644 index 0000000..5cb09b4 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/TempService/TempCommandServiceImpl.java @@ -0,0 +1,10 @@ +package umc.study.service.TempService; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class TempCommandServiceImpl implements TempCommandService{ + +} diff --git a/week5/spring/src/main/java/umc/study/service/TempService/TempQueryService.java b/week5/spring/src/main/java/umc/study/service/TempService/TempQueryService.java new file mode 100644 index 0000000..53687d0 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/TempService/TempQueryService.java @@ -0,0 +1,6 @@ +package umc.study.service.TempService; + +public interface TempQueryService { + + void CheckFlag(Integer flag); +} diff --git a/week5/spring/src/main/java/umc/study/service/TempService/TempQueryServiceImpl.java b/week5/spring/src/main/java/umc/study/service/TempService/TempQueryServiceImpl.java new file mode 100644 index 0000000..0e3ee86 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/TempService/TempQueryServiceImpl.java @@ -0,0 +1,17 @@ +package umc.study.service.TempService; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import umc.study.apiPayload.code.status.ErrorStatus; +import umc.study.apiPayload.exception.handler.TempHandler; + +@Service +@RequiredArgsConstructor +public class TempQueryServiceImpl implements TempQueryService{ + + @Override + public void CheckFlag(Integer flag) { + if (flag == 1) + throw new TempHandler(ErrorStatus.TEMP_EXCEPTION); + } +} diff --git a/week5/spring/src/main/java/umc/study/service/UserMissionService/UserMissionService.java b/week5/spring/src/main/java/umc/study/service/UserMissionService/UserMissionService.java new file mode 100644 index 0000000..b308833 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/UserMissionService/UserMissionService.java @@ -0,0 +1,64 @@ +package umc.study.service.UserMissionService; + +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 umc.study.converter.MissionConverter; +import umc.study.domain.Mission; +import umc.study.domain.User; +import umc.study.domain.UserMission; +import umc.study.domain.enums.Status; +import umc.study.repository.MissionRepository.MissionRepository; +import umc.study.repository.UserMissionRepository.UserMissionRepository; +import umc.study.repository.UserRepository.UserRepository; +import umc.study.web.dto.MissionResponseDTO; +import umc.study.web.dto.UserMissionRequestDTO; +import umc.study.web.dto.UserMissionResponseDTO; + +@Service +@RequiredArgsConstructor +public class UserMissionService { + + private final UserMissionRepository userMissionRepository; + private final MissionRepository missionRepository; + private final UserRepository userRepository; + + private final MissionConverter missionConverter; + + + @Transactional + public UserMissionResponseDTO possibleMission(UserMissionRequestDTO requestDTO) { + // 유저와 미션 엔티티 조회 + User user = userRepository.findById(1L) // 동동의 고정 userId + .orElseThrow(() -> new IllegalArgumentException("사용자를 찾을 수 없습니다.")); + Mission mission = missionRepository.findById(requestDTO.getMissionId()) + .orElseThrow(() -> new IllegalArgumentException("미션을 찾을 수 없습니다.")); + + // UserMission 엔티티 생성 및 저장 + UserMission userMission = UserMission.builder() + .user(user) + .mission(mission) + .build(); + + userMissionRepository.save(userMission); + + return new UserMissionResponseDTO(userMission.getId(), user.getId(), mission.getId()); + } + + @Transactional(readOnly = true) + public Page getMissionsByUser(Long userId, Pageable pageable) { + Page userMissions = userMissionRepository.findAllByUserId(userId, pageable); + return userMissions.map(userMission -> + MissionConverter.toResponseDTO(userMission.getMission())); + } + + @Transactional + public Page completeMissionsByUser(Long userId, Pageable pageable) { + Page userMissions = userMissionRepository.findByUserIdAndMissionStatus(userId, Status.ACTIVE, pageable); + userMissions.forEach(userMission -> userMission.getMission().setStatus(Status.INACTIVE)); + + return userMissions.map(userMission -> missionConverter.toResponseDTO(userMission.getMission())); + } +} diff --git a/week5/spring/src/main/java/umc/study/service/UserService/UserCommandService.java b/week5/spring/src/main/java/umc/study/service/UserService/UserCommandService.java new file mode 100644 index 0000000..3520dd8 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/UserService/UserCommandService.java @@ -0,0 +1,10 @@ +package umc.study.service.UserService; + +import umc.study.domain.User; +import umc.study.web.dto.UserRequestDTO; +import umc.study.web.dto.UserResponseDTO; + +public interface UserCommandService { + User joinUser(UserRequestDTO.JoinDto request); + UserResponseDTO.JoinResultDTO join(UserRequestDTO.JoinDto request); +} diff --git a/week5/spring/src/main/java/umc/study/service/UserService/UserCommandServiceImpl.java b/week5/spring/src/main/java/umc/study/service/UserService/UserCommandServiceImpl.java new file mode 100644 index 0000000..94b76a2 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/UserService/UserCommandServiceImpl.java @@ -0,0 +1,55 @@ +package umc.study.service.UserService; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import umc.study.apiPayload.code.status.ErrorStatus; +import umc.study.apiPayload.exception.handler.FoodHandler; +import umc.study.converter.UserConverter; +import umc.study.converter.UserFavoriteFoodConverter; +import umc.study.domain.Food; +import umc.study.domain.User; +import umc.study.domain.UserFavoriteFoods; +import umc.study.domain.enums.Gender; +import umc.study.repository.UserRepository.FoodRepository; +import umc.study.repository.UserRepository.UserRepository; +import umc.study.web.dto.UserRequestDTO; +import umc.study.web.dto.UserResponseDTO; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class UserCommandServiceImpl implements UserCommandService { + + private final UserRepository userRepository; + + private final FoodRepository foodRepository; + + @Override + @Transactional + public User joinUser(UserRequestDTO.JoinDto request) { + + User user = UserConverter.toUser(request); + + List foodList = request.getFavoriteFoodIds().stream() + .map(categoryId -> + foodRepository.findById(categoryId) + .orElseThrow(() -> new FoodHandler(ErrorStatus.FOOD_CATEGORY_NOT_FOUND)) + ).collect(Collectors.toList()); + + List userFavoriteFoodsList = UserFavoriteFoodConverter.toUserFavoriteFoodsList(foodList); + + userFavoriteFoodsList.forEach(userFavoriteFoods -> {userFavoriteFoods.setUser(user);}); + + return userRepository.save(user); + + } + + @Override + public UserResponseDTO.JoinResultDTO join(UserRequestDTO.JoinDto request) { + User user = joinUser(request); + return UserConverter.toJoinResultDTO(user); + } +} diff --git a/week5/spring/src/main/java/umc/study/service/UserService/UserQueryService.java b/week5/spring/src/main/java/umc/study/service/UserService/UserQueryService.java new file mode 100644 index 0000000..ad41fac --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/UserService/UserQueryService.java @@ -0,0 +1,4 @@ +package umc.study.service.UserService; + +public interface UserQueryService { +} diff --git a/week5/spring/src/main/java/umc/study/service/UserService/UserQueryServiceImpl.java b/week5/spring/src/main/java/umc/study/service/UserService/UserQueryServiceImpl.java new file mode 100644 index 0000000..ab8492d --- /dev/null +++ b/week5/spring/src/main/java/umc/study/service/UserService/UserQueryServiceImpl.java @@ -0,0 +1,4 @@ +package umc.study.service.UserService; + +public class UserQueryServiceImpl { +} diff --git a/week5/spring/src/main/java/umc/study/validation/annotation/CheckPage.java b/week5/spring/src/main/java/umc/study/validation/annotation/CheckPage.java new file mode 100644 index 0000000..b9730e1 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/annotation/CheckPage.java @@ -0,0 +1,22 @@ +package umc.study.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.study.validation.validator.CheckPageValidator; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Constraint(validatedBy = CheckPageValidator.class) +@Target({ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +public @interface CheckPage { + + String message() default "잘못된 페이지 정보입니다."; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/week5/spring/src/main/java/umc/study/validation/annotation/ExistCategories.java b/week5/spring/src/main/java/umc/study/validation/annotation/ExistCategories.java new file mode 100644 index 0000000..3a77665 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/annotation/ExistCategories.java @@ -0,0 +1,18 @@ +package umc.study.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.study.validation.validator.CategoriesExistValidator; + +import java.lang.annotation.*; + +@Documented +@Constraint(validatedBy = CategoriesExistValidator.class) +@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistCategories { + + String message() default "해당하는 카테고리가 존재하지 않습니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/week5/spring/src/main/java/umc/study/validation/annotation/ExistStores.java b/week5/spring/src/main/java/umc/study/validation/annotation/ExistStores.java new file mode 100644 index 0000000..8c4c38f --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/annotation/ExistStores.java @@ -0,0 +1,22 @@ +package umc.study.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.study.validation.validator.StoreExistsValidator; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Constraint(validatedBy = StoreExistsValidator.class) +@Target({ElementType.PARAMETER, ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface ExistStores { + + String message() default "존재하지 않는 가게 ID입니다."; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/week5/spring/src/main/java/umc/study/validation/annotation/MissionPossible.java b/week5/spring/src/main/java/umc/study/validation/annotation/MissionPossible.java new file mode 100644 index 0000000..ff6e3f8 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/annotation/MissionPossible.java @@ -0,0 +1,17 @@ +package umc.study.validation.annotation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import umc.study.validation.validator.MissionPossibleValidator; + +import java.lang.annotation.*; + +@Documented +@Constraint(validatedBy = MissionPossibleValidator.class) +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface MissionPossible { + String message() default "이미 도전 중인 미션입니다."; + Class[] groups() default {}; + Class[] payload() default {}; +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/validation/validator/CategoriesExistValidator.java b/week5/spring/src/main/java/umc/study/validation/validator/CategoriesExistValidator.java new file mode 100644 index 0000000..38abf1a --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/validator/CategoriesExistValidator.java @@ -0,0 +1,36 @@ +package umc.study.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import umc.study.apiPayload.code.status.ErrorStatus; +import umc.study.repository.UserRepository.FoodRepository; +import umc.study.validation.annotation.ExistCategories; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class CategoriesExistValidator implements ConstraintValidator> { + private final FoodRepository foodRepository; + + @Override + public void initialize(ExistCategories constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = values.stream() + .allMatch(value -> foodRepository.existsById(value)); + + if (!isValid) { + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate(ErrorStatus.FOOD_CATEGORY_NOT_FOUND.toString()).addConstraintViolation(); + } + + return isValid; + + } +} diff --git a/week5/spring/src/main/java/umc/study/validation/validator/CheckPageValidator.java b/week5/spring/src/main/java/umc/study/validation/validator/CheckPageValidator.java new file mode 100644 index 0000000..6d0027d --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/validator/CheckPageValidator.java @@ -0,0 +1,20 @@ +package umc.study.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import umc.study.validation.annotation.CheckPage; + +public class CheckPageValidator implements ConstraintValidator { + + @Override + public boolean isValid(Integer page, ConstraintValidatorContext context) { + if (page == null || page <= 0) { + return false; + } + return true; + } + + public static Integer adjustPage(Integer page) { + return page - 1; + } +} diff --git a/week5/spring/src/main/java/umc/study/validation/validator/MissionPossibleValidator.java b/week5/spring/src/main/java/umc/study/validation/validator/MissionPossibleValidator.java new file mode 100644 index 0000000..8cc433b --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/validator/MissionPossibleValidator.java @@ -0,0 +1,22 @@ +package umc.study.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import umc.study.repository.UserMissionRepository.UserMissionRepository; +import umc.study.validation.annotation.MissionPossible; + +@RequiredArgsConstructor +public class MissionPossibleValidator implements ConstraintValidator { + + private final UserMissionRepository userMissionRepository; + + @Override + public boolean isValid(Long missionId, ConstraintValidatorContext context) { + // 유저 ID는 고정값(1) 기준으로 확인 + Long userId = 1L; + + // 이미 도전 중인 미션인지 확인 + return !userMissionRepository.existsByUserIdAndMissionId(userId, missionId); + } +} \ No newline at end of file diff --git a/week5/spring/src/main/java/umc/study/validation/validator/StoreExistsValidator.java b/week5/spring/src/main/java/umc/study/validation/validator/StoreExistsValidator.java new file mode 100644 index 0000000..35e86ab --- /dev/null +++ b/week5/spring/src/main/java/umc/study/validation/validator/StoreExistsValidator.java @@ -0,0 +1,18 @@ +package umc.study.validation.validator; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import lombok.RequiredArgsConstructor; +import umc.study.repository.StoreRepository.StoreRepository; +import umc.study.validation.annotation.ExistStores; + +@RequiredArgsConstructor +public class StoreExistsValidator implements ConstraintValidator { + + private final StoreRepository storeRepository; + + @Override + public boolean isValid(Long storeId, ConstraintValidatorContext context) { + return storeId != null && storeRepository.existsById(storeId); + } +} diff --git a/week5/spring/src/main/java/umc/study/web/controller/MissionController.java b/week5/spring/src/main/java/umc/study/web/controller/MissionController.java new file mode 100644 index 0000000..038610f --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/controller/MissionController.java @@ -0,0 +1,57 @@ +package umc.study.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import umc.study.apiPayload.ApiResponse; +import umc.study.service.MissionService.MissionService; +import umc.study.service.UserMissionService.UserMissionService; +import umc.study.validation.annotation.CheckPage; +import umc.study.validation.validator.CheckPageValidator; +import umc.study.web.dto.MissionRequestDTO; +import umc.study.web.dto.MissionResponseDTO; + +@RestController +@RequestMapping("/stores") +@RequiredArgsConstructor +public class MissionController { + + private final MissionService missionService; + private final UserMissionService userMissionService; + + @PostMapping("/{storeId}/missions") + public ResponseEntity> addMission( + @Valid @RequestBody MissionRequestDTO requestDTO) { + MissionResponseDTO responseDTO = missionService.addMission(requestDTO); + return ResponseEntity.ok(ApiResponse.onSuccess(responseDTO)); + } + + @Operation(summary = "특정 가게의 미션 목록 조회", description = "특정 가게(Store)의 미션(Mission) 목록을 페이지네이션으로 조회") + @GetMapping("/missions/store") + public Page getMissionsByStore( + @Parameter(description = "가게 ID", example = "1") + @RequestParam(name = "storeId") Long storeId, + @Parameter(description = "조회할 페이지 번호 (1 이상)", example = "1") + @CheckPage @RequestParam(name = "page") Integer page) { + + Integer adjustedPage = CheckPageValidator.adjustPage(page); + Pageable pageable = PageRequest.of(adjustedPage, 10); + + return missionService.getMissionsByStore(storeId, pageable); + } + + @PatchMapping("/missions/{missionId}/status") + @Operation(summary = "미션 상태 변경", description = "특정 미션의 상태를 INACTIVE로 변경") + public ResponseEntity updateMissionStatus( + @PathVariable Long missionId) { + missionService.updateMissionStatus(missionId); + return ResponseEntity.ok("Mission status updated to INACTIVE"); + } + +} diff --git a/week5/spring/src/main/java/umc/study/web/controller/RegionController.java b/week5/spring/src/main/java/umc/study/web/controller/RegionController.java new file mode 100644 index 0000000..70fb2ef --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/controller/RegionController.java @@ -0,0 +1,26 @@ +package umc.study.web.controller; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import umc.study.service.RegionService.RegionService; +import umc.study.web.dto.StoreRequestDTO; +import umc.study.web.dto.StoreResponseDTO; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/regions") +public class RegionController { + + private final RegionService regionService; + + // 특정 지역에 가게 추가 API + @PostMapping("/{regionId}/stores") + public ResponseEntity addStoreToRegion( + @PathVariable Long regionId, + @RequestBody @Valid StoreRequestDTO storeRequestDTO) { + StoreResponseDTO response = regionService.addStoreToRegion(regionId, storeRequestDTO); + return ResponseEntity.ok(response); + } +} diff --git a/week5/spring/src/main/java/umc/study/web/controller/ReviewController.java b/week5/spring/src/main/java/umc/study/web/controller/ReviewController.java new file mode 100644 index 0000000..624f42d --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/controller/ReviewController.java @@ -0,0 +1,45 @@ +package umc.study.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import umc.study.service.ReviewService.ReviewService; +import umc.study.validation.annotation.CheckPage; +import umc.study.validation.validator.CheckPageValidator; +import umc.study.web.dto.ReviewRequestDTO; +import umc.study.web.dto.ReviewResponseDTO; + +@RestController +@RequestMapping("/stores") +@RequiredArgsConstructor +public class ReviewController { + + private final ReviewService reviewService; + + @PostMapping("/{storeId}/reviews") + public ResponseEntity addReviewToStore(@RequestBody @Valid ReviewRequestDTO reviewRequestDTO) { + ReviewResponseDTO response = reviewService.addReviewToStore(reviewRequestDTO); + return ResponseEntity.ok(response); + } + + // 9주차 워크북 : 내가 작성한 리뷰 목록 API + @Operation(summary = "내가 작성한 리뷰 목록 보기", description = "사용자가 작성한 리뷰 목록을 페이지네이션으로 조회") + @GetMapping("/reviews/my") + public Page getMyReviews( + @Parameter(description = "조회할 페이지 번호 (1 이상)", example = "1") + @CheckPage @RequestParam(name = "page") Integer page) { + + // 페이지 번호 조정 + Integer adjustedPage = CheckPageValidator.adjustPage(page); + Pageable pageable = PageRequest.of(adjustedPage, 10); + + return reviewService.getMyReviews(pageable); + } + +} diff --git a/week5/spring/src/main/java/umc/study/web/controller/TempRestController.java b/week5/spring/src/main/java/umc/study/web/controller/TempRestController.java new file mode 100644 index 0000000..76e1761 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/controller/TempRestController.java @@ -0,0 +1,32 @@ +package umc.study.web.controller; + +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; +import umc.study.apiPayload.ApiResponse; +import umc.study.converter.TempConverter; +import umc.study.service.TempService.TempQueryService; +import umc.study.web.dto.TempResponse; + +@RestController +@RequestMapping("/temp") +@RequiredArgsConstructor +public class TempRestController { + + private final TempQueryService tempQueryService; + + @GetMapping("/test") + public ApiResponse testAPI(){ + + return ApiResponse.onSuccess(TempConverter.toTempTestDTO()); + } + + @GetMapping("/exception") + public ApiResponse exceptionAPI(@RequestParam Integer flag){ + tempQueryService.CheckFlag(flag); + return ApiResponse.onSuccess(TempConverter.toTempExceptionDTO(flag)); + } +} + diff --git a/week5/spring/src/main/java/umc/study/web/controller/UserMissionController.java b/week5/spring/src/main/java/umc/study/web/controller/UserMissionController.java new file mode 100644 index 0000000..04eeb5e --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/controller/UserMissionController.java @@ -0,0 +1,47 @@ +package umc.study.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import umc.study.service.UserMissionService.UserMissionService; +import umc.study.validation.annotation.CheckPage; +import umc.study.validation.validator.CheckPageValidator; +import umc.study.web.dto.MissionResponseDTO; +import umc.study.web.dto.UserMissionRequestDTO; +import umc.study.web.dto.UserMissionResponseDTO; + +@RestController +@RequestMapping("/missions/challenges") +@RequiredArgsConstructor +public class UserMissionController { + + private final UserMissionService userMissionService; + + @Operation(summary = "User 동동의 미션 목록에 미션 추가") + @PostMapping + public ResponseEntity challengeMission( + @RequestBody @Valid UserMissionRequestDTO requestDTO) { + UserMissionResponseDTO responseDTO = userMissionService.possibleMission(requestDTO); + return ResponseEntity.ok(responseDTO); + } + + @Operation(summary = "내가 진행 중인 미션 조회", description = "진행 중인 미션을 페이지 단위로 조회") + @GetMapping("/my-missions") + public Page getMyMissions( + @Parameter(description = "User ID (기본값: 1)", example = "1") + @RequestParam(defaultValue = "1") Long userId, + @CheckPage @RequestParam(name = "page") Integer page) { + + // 페이지 번호 조정 + Integer adjustedPage = CheckPageValidator.adjustPage(page); + Pageable pageable = PageRequest.of(adjustedPage, 10); + + return userMissionService.getMissionsByUser(userId, pageable); + } +} diff --git a/week5/spring/src/main/java/umc/study/web/controller/UserRestController.java b/week5/spring/src/main/java/umc/study/web/controller/UserRestController.java new file mode 100644 index 0000000..531333d --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/controller/UserRestController.java @@ -0,0 +1,41 @@ +package umc.study.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import umc.study.converter.UserConverter; +import umc.study.domain.User; +import umc.study.service.UserService.UserCommandService; +import umc.study.web.dto.UserRequestDTO; +import umc.study.web.dto.UserResponseDTO; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/users") +public class UserRestController { + private final UserCommandService userCommandService; + + @PostMapping("/") + @Operation(summary = "회원 가입", description = "회원 가입 API입니다.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "회원 가입 성공"), + @ApiResponse(responseCode = "400", description = "잘못된 요청") + }) + public ResponseEntity join(@RequestBody @Valid UserRequestDTO.JoinDto request) { + // 회원 가입 처리 + User user = userCommandService.joinUser(request); + + // DTO 변환 + UserResponseDTO.JoinResultDTO resultDTO = UserConverter.toJoinResultDTO(user); + + // 성공 응답 반환 + return ResponseEntity.ok(resultDTO); + } +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/MissionRequestDTO.java b/week5/spring/src/main/java/umc/study/web/dto/MissionRequestDTO.java new file mode 100644 index 0000000..635c1ee --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/MissionRequestDTO.java @@ -0,0 +1,32 @@ +package umc.study.web.dto; + +import jakarta.validation.constraints.Future; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; +import umc.study.validation.annotation.ExistStores; +import umc.study.validation.annotation.ExistStores; + +import java.time.LocalDateTime; + +@Getter +@Setter +public class MissionRequestDTO { + + @NotNull + @ExistStores + private Long storeId; + + @NotBlank + private String missionDescription; + + @NotNull + @Min(value = 1, message = "미션 포인트 보상은 반드시 0포인트 이상이어야 합니다.") + private Integer missionPoint; + + @NotNull + @Future(message = "Deadline은 반드시 미래의 시간대여야 합니다.") + private LocalDateTime deadline; +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/MissionResponseDTO.java b/week5/spring/src/main/java/umc/study/web/dto/MissionResponseDTO.java new file mode 100644 index 0000000..7f4f525 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/MissionResponseDTO.java @@ -0,0 +1,20 @@ +package umc.study.web.dto; + +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +@Builder +public class MissionResponseDTO { + private Long id; + private Long storeId; +// private String storeName; + private String missionDescription; + private Integer missionPoint; + private LocalDateTime deadline; + private String status; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/ReviewRequestDTO.java b/week5/spring/src/main/java/umc/study/web/dto/ReviewRequestDTO.java new file mode 100644 index 0000000..2040855 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/ReviewRequestDTO.java @@ -0,0 +1,30 @@ +package umc.study.web.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Getter; +import lombok.Setter; +import umc.study.domain.enums.ReviewScope; +import umc.study.validation.annotation.ExistStores; + +@Getter +@Setter +public class ReviewRequestDTO { + + @NotNull + @ExistStores + private Long storeId; + + @NotNull + private Long userId; + + @NotBlank + @Size(max = 500, message = "최대 500자까지 입력 가능합니다.") + private String reviewContent; + + @NotNull(message = "별점 후기가 필요합니다.") + private ReviewScope reviewScope; + + private String reviewImg; // 선택 +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/ReviewResponseDTO.java b/week5/spring/src/main/java/umc/study/web/dto/ReviewResponseDTO.java new file mode 100644 index 0000000..69e2be1 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/ReviewResponseDTO.java @@ -0,0 +1,18 @@ +package umc.study.web.dto; + +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +@Builder +public class ReviewResponseDTO { + private Long id; + private Long storeId; + private Long userId; + private String reviewContent; + private String reviewImg; + private String reviewScope; + private LocalDateTime createdAt; +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/StoreRequestDTO.java b/week5/spring/src/main/java/umc/study/web/dto/StoreRequestDTO.java new file mode 100644 index 0000000..4ea3e29 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/StoreRequestDTO.java @@ -0,0 +1,24 @@ +package umc.study.web.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Getter; +import umc.study.domain.enums.Status; + +@Getter +public class StoreRequestDTO { + + @NotBlank + @Size(max = 50, message = "가게 이름을 50자를 넘기지 마십쇼") + private String storeName; + + @NotBlank + private String address; + + @NotNull + private Long foodId; + + @NotNull + private Status status; +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/StoreResponseDTO.java b/week5/spring/src/main/java/umc/study/web/dto/StoreResponseDTO.java new file mode 100644 index 0000000..d026a88 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/StoreResponseDTO.java @@ -0,0 +1,19 @@ +package umc.study.web.dto; + +import lombok.Builder; +import lombok.Getter; +import umc.study.domain.enums.Status; + +import java.math.BigDecimal; + +@Getter +@Builder +public class StoreResponseDTO { + + private Long id; + private String storeName; + private String address; + private BigDecimal storeScope; + private Long regionId; + private Status status; +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/TempRequest.java b/week5/spring/src/main/java/umc/study/web/dto/TempRequest.java new file mode 100644 index 0000000..ae31723 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/TempRequest.java @@ -0,0 +1,4 @@ +package umc.study.web.dto; + +public class TempRequest { +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/TempResponse.java b/week5/spring/src/main/java/umc/study/web/dto/TempResponse.java new file mode 100644 index 0000000..2ee4b9c --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/TempResponse.java @@ -0,0 +1,25 @@ +package umc.study.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +public class TempResponse { + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class TempTestDTO{ + String testString; + } + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class TempExceptionDTO{ + Integer flag; + } +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/UserMissionRequestDTO.java b/week5/spring/src/main/java/umc/study/web/dto/UserMissionRequestDTO.java new file mode 100644 index 0000000..9417f7a --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/UserMissionRequestDTO.java @@ -0,0 +1,13 @@ +package umc.study.web.dto; + +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import umc.study.validation.annotation.MissionPossible; + +@Getter +public class UserMissionRequestDTO { + + @NotNull(message = "도전할 미션 ID는 필수입니다.") + @MissionPossible + private Long missionId; +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/UserMissionResponseDTO.java b/week5/spring/src/main/java/umc/study/web/dto/UserMissionResponseDTO.java new file mode 100644 index 0000000..991914a --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/UserMissionResponseDTO.java @@ -0,0 +1,12 @@ +package umc.study.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class UserMissionResponseDTO { + private Long id; + private Long userId; + private Long missionId; +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/UserRequestDTO.java b/week5/spring/src/main/java/umc/study/web/dto/UserRequestDTO.java new file mode 100644 index 0000000..a596e80 --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/UserRequestDTO.java @@ -0,0 +1,32 @@ +package umc.study.web.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Getter; +import umc.study.domain.enums.Gender; +import umc.study.validation.annotation.ExistCategories; + +import java.time.LocalDate; +import java.util.List; + +public class UserRequestDTO { + @Getter + public static class JoinDto{ + @NotBlank + String name; + + @NotNull + String gender; + + @NotNull + LocalDate userBirth; + + @Size(min = 3, max = 10) + String userAddress; + + @ExistCategories + List favoriteFoodIds; + } +} diff --git a/week5/spring/src/main/java/umc/study/web/dto/UserResponseDTO.java b/week5/spring/src/main/java/umc/study/web/dto/UserResponseDTO.java new file mode 100644 index 0000000..bdaa02b --- /dev/null +++ b/week5/spring/src/main/java/umc/study/web/dto/UserResponseDTO.java @@ -0,0 +1,19 @@ +package umc.study.web.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +public class UserResponseDTO { + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class JoinResultDTO{ + Long userId; + LocalDateTime createdAt; + } +} diff --git a/week5/spring/src/main/resources/application.yml b/week5/spring/src/main/resources/application.yml new file mode 100644 index 0000000..ab71e3f --- /dev/null +++ b/week5/spring/src/main/resources/application.yml @@ -0,0 +1,19 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/springW + username: root + password: kimhy119@ + sql: + init: + mode: never + jpa: + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL8Dialect + show_sql: true + format_sql: true + use_sql_comments: true + hbm2ddl: + auto: update + default_batch_fetch_size: 1000 \ No newline at end of file diff --git a/week5/spring/src/test/java/umc/spring/ApplicationTests.java b/week5/spring/src/test/java/umc/spring/ApplicationTests.java new file mode 100644 index 0000000..dc36e6c --- /dev/null +++ b/week5/spring/src/test/java/umc/spring/ApplicationTests.java @@ -0,0 +1,13 @@ +package umc.spring; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ApplicationTests { + + @Test + void contextLoads() { + } + +}