diff --git a/.DS_Store b/.DS_Store index 5577e42..f13be0f 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..99001b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +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/ + +### 민감정보 ### +.env +application.yaml diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..2b0c411 --- /dev/null +++ b/build.gradle @@ -0,0 +1,45 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.5' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' + implementation 'org.springframework.boot:spring-boot-starter-web' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + runtimeOnly 'com.mysql:mysql-connector-j' + + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-api:2.5.0' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + implementation 'org.springframework.boot:spring-boot-starter-validation' +} + +tasks.named('test') { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..aaaabb3 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b4ccb81 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'umc' diff --git a/src/.DS_Store b/src/.DS_Store new file mode 100644 index 0000000..17d2868 Binary files /dev/null and b/src/.DS_Store differ diff --git a/src/main/.DS_Store b/src/main/.DS_Store new file mode 100644 index 0000000..963aa85 Binary files /dev/null and b/src/main/.DS_Store differ diff --git a/src/main/java/umc/UmcApplication.java b/src/main/java/umc/UmcApplication.java new file mode 100644 index 0000000..b36f64a --- /dev/null +++ b/src/main/java/umc/UmcApplication.java @@ -0,0 +1,13 @@ +package umc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class UmcApplication { + + public static void main(String[] args) { + SpringApplication.run(UmcApplication.class, args); + } + +} diff --git a/src/main/java/umc/domain/.DS_Store b/src/main/java/umc/domain/.DS_Store new file mode 100644 index 0000000..ba6e49c Binary files /dev/null and b/src/main/java/umc/domain/.DS_Store differ diff --git a/src/main/java/umc/domain/mission/.DS_Store b/src/main/java/umc/domain/mission/.DS_Store new file mode 100644 index 0000000..dc8af7f Binary files /dev/null and b/src/main/java/umc/domain/mission/.DS_Store differ diff --git a/src/main/java/umc/domain/mission/controller/MissionController.java b/src/main/java/umc/domain/mission/controller/MissionController.java new file mode 100644 index 0000000..ceae66d --- /dev/null +++ b/src/main/java/umc/domain/mission/controller/MissionController.java @@ -0,0 +1,70 @@ +package umc.domain.mission.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.*; +import umc.domain.mission.dto.response.MissionResponseDto; + +import umc.domain.mission.service.MissionQueryService; +import umc.domain.user.entity.mapping.MissionStatus; +import umc.domain.user.entity.mapping.UserMission; +import umc.global.apiPayload.ApiResponse; +import umc.global.apiPayload.code.status.GeneralSuccessCode; +import umc.global.common.PageResponseDto; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/missions") +public class MissionController { + + private final MissionQueryService missionQueryService; + + @GetMapping("/my") + public ApiResponse> getMyMissions( + @RequestHeader(name = "userId") Long userId, + @RequestParam(name = "status") MissionStatus status, + @RequestParam(name = "page") Integer page, + @RequestParam(name = "size") Integer size + ) { + // JPA 페이지는 0부터 시작하므로 page - 1 처리 + Page userMissionPage = missionQueryService.getMyMissions(userId, status, page - 1); + + // Entity 리스트를 7주차 응답 규격인 DTO 리스트로 변환 + List data = userMissionPage.stream() + .map(um -> MissionResponseDto.MyMissionPreviewDto.builder() + .missionId(um.getMission().getId()) + .storeName(um.getMission().getStore().getName()) + .reward(um.getMission().getReward()) + .missionSpec(um.getMission().getMissionSpec()) + .deadline(um.getMission().getDeadline()) + .build()) + .collect(Collectors.toList()); + + // 공통 페이징 응답 객체 포장 + PageResponseDto response = PageResponseDto.builder() + .data(data) + .listSize(userMissionPage.getSize()) + .totalPage(userMissionPage.getTotalPages()) + .totalElements(userMissionPage.getTotalElements()) + .isFirst(userMissionPage.isFirst()) + .isLast(userMissionPage.isLast()) + .build(); + + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } + + @PatchMapping("/{missionId}/complete") + public ApiResponse completeMission( + @PathVariable(name = "missionId") Long missionId + ) { + MissionResponseDto.CompleteMissionResultDto dummyResponse = MissionResponseDto.CompleteMissionResultDto.builder() + .missionId(missionId) + .completedAt(LocalDateTime.now()) + .build(); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, dummyResponse); + } +} \ No newline at end of file diff --git a/src/main/java/umc/domain/mission/dto/.DS_Store b/src/main/java/umc/domain/mission/dto/.DS_Store new file mode 100644 index 0000000..120fb72 Binary files /dev/null and b/src/main/java/umc/domain/mission/dto/.DS_Store differ diff --git a/src/main/java/umc/domain/mission/dto/response/MissionResponseDto.java b/src/main/java/umc/domain/mission/dto/response/MissionResponseDto.java new file mode 100644 index 0000000..a76abee --- /dev/null +++ b/src/main/java/umc/domain/mission/dto/response/MissionResponseDto.java @@ -0,0 +1,33 @@ +package umc.domain.mission.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class MissionResponseDto { + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MyMissionPreviewDto { + private Long missionId; + private String storeName; + private Integer reward; + private String missionSpec; + private LocalDate deadline; + } + + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class CompleteMissionResultDto { + private Long missionId; + private LocalDateTime completedAt; + } +} \ No newline at end of file diff --git a/src/main/java/umc/domain/mission/entity/Mission.java b/src/main/java/umc/domain/mission/entity/Mission.java new file mode 100644 index 0000000..03142de --- /dev/null +++ b/src/main/java/umc/domain/mission/entity/Mission.java @@ -0,0 +1,29 @@ +package umc.domain.mission.entity; + +import jakarta.persistence.*; +import lombok.*; +import umc.global.common.BaseEntity; + +import java.time.LocalDate; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Mission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Integer reward; + + private LocalDate deadline; + + private String missionSpec; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; +} \ No newline at end of file diff --git a/src/main/java/umc/domain/mission/entity/Region.java b/src/main/java/umc/domain/mission/entity/Region.java new file mode 100644 index 0000000..5ce423f --- /dev/null +++ b/src/main/java/umc/domain/mission/entity/Region.java @@ -0,0 +1,4 @@ +package umc.domain.mission.entity; + +public class Region { +} diff --git a/src/main/java/umc/domain/mission/entity/Store.java b/src/main/java/umc/domain/mission/entity/Store.java new file mode 100644 index 0000000..55427f5 --- /dev/null +++ b/src/main/java/umc/domain/mission/entity/Store.java @@ -0,0 +1,29 @@ +package umc.domain.mission.entity; + +import jakarta.persistence.*; +import lombok.*; +import umc.global.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Store extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 50) + private String name; + + @Column(nullable = false, length = 50) + private String address; + + private Float score; + +// @ManyToOne(fetch = FetchType.LAZY) +// @JoinColumn(name = "region_id") +// private Region region; +} \ No newline at end of file diff --git a/src/main/java/umc/domain/mission/entity/mapping/Status.java b/src/main/java/umc/domain/mission/entity/mapping/Status.java new file mode 100644 index 0000000..a64e71a --- /dev/null +++ b/src/main/java/umc/domain/mission/entity/mapping/Status.java @@ -0,0 +1,4 @@ +package umc.domain.mission.entity.mapping; + +public class Status { +} diff --git a/src/main/java/umc/domain/mission/repository/MissionRepository.java b/src/main/java/umc/domain/mission/repository/MissionRepository.java new file mode 100644 index 0000000..853d5e6 --- /dev/null +++ b/src/main/java/umc/domain/mission/repository/MissionRepository.java @@ -0,0 +1,7 @@ +package umc.domain.mission.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.domain.mission.entity.Mission; + +public interface MissionRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/umc/domain/mission/repository/UserMissionRepository.java b/src/main/java/umc/domain/mission/repository/UserMissionRepository.java new file mode 100644 index 0000000..6b94acc --- /dev/null +++ b/src/main/java/umc/domain/mission/repository/UserMissionRepository.java @@ -0,0 +1,20 @@ +package umc.domain.mission.repository; + +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.domain.user.entity.mapping.MissionStatus; +import umc.domain.user.entity.mapping.UserMission; + +public interface UserMissionRepository extends JpaRepository { + + @Query("SELECT um FROM UserMission um JOIN FETCH um.mission m JOIN FETCH m.store s " + + "WHERE um.user.id = :userId AND um.status = :status") + Page findMyMissions( + @Param("userId") Long userId, + @Param("status") MissionStatus status, + Pageable pageable + ); +} \ No newline at end of file diff --git a/src/main/java/umc/domain/mission/service/MissionQueryService.java b/src/main/java/umc/domain/mission/service/MissionQueryService.java new file mode 100644 index 0000000..a3c2ec3 --- /dev/null +++ b/src/main/java/umc/domain/mission/service/MissionQueryService.java @@ -0,0 +1,9 @@ +package umc.domain.mission.service; + +import org.springframework.data.domain.Page; +import umc.domain.user.entity.mapping.MissionStatus; +import umc.domain.user.entity.mapping.UserMission; + +public interface MissionQueryService { + Page getMyMissions(Long userId, MissionStatus status, Integer page); +} \ No newline at end of file diff --git a/src/main/java/umc/domain/mission/service/MissionQueryServiceImpl.java b/src/main/java/umc/domain/mission/service/MissionQueryServiceImpl.java new file mode 100644 index 0000000..0cce041 --- /dev/null +++ b/src/main/java/umc/domain/mission/service/MissionQueryServiceImpl.java @@ -0,0 +1,23 @@ +package umc.domain.mission.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import umc.domain.mission.repository.UserMissionRepository; +import umc.domain.user.entity.mapping.MissionStatus; +import umc.domain.user.entity.mapping.UserMission; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class MissionQueryServiceImpl implements MissionQueryService { + + private final UserMissionRepository userMissionRepository; + + @Override + public Page getMyMissions(Long userId, MissionStatus status, Integer page) { + return userMissionRepository.findMyMissions(userId, status, PageRequest.of(page, 10)); + } +} \ No newline at end of file diff --git a/src/main/java/umc/domain/review/.DS_Store b/src/main/java/umc/domain/review/.DS_Store new file mode 100644 index 0000000..dc8af7f Binary files /dev/null and b/src/main/java/umc/domain/review/.DS_Store differ diff --git a/src/main/java/umc/domain/review/controller/ReviewController.java b/src/main/java/umc/domain/review/controller/ReviewController.java new file mode 100644 index 0000000..dfc461e --- /dev/null +++ b/src/main/java/umc/domain/review/controller/ReviewController.java @@ -0,0 +1,83 @@ +package umc.domain.review.controller; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Slice; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; +import org.springframework.web.bind.annotation.*; +import umc.domain.review.dto.request.ReviewRequestDto; +import umc.domain.review.dto.response.ReviewResponseDto; +import umc.domain.review.entity.Review; +import umc.domain.review.service.ReviewCommandServiceImpl; +import umc.domain.review.service.ReviewQueryServiceImpl; +import umc.global.apiPayload.ApiResponse; +import umc.global.apiPayload.code.status.GeneralSuccessCode; +import umc.global.common.CursorResponseDto; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/reviews") +public class ReviewController { + private final ReviewQueryServiceImpl reviewQueryService; + private final ReviewCommandServiceImpl reviewCommandService; + private final NamedParameterJdbcOperations namedParameterJdbcOperations; + + @PostMapping("/missions/{missionId}/reviews") + public ApiResponse createReview( + @RequestHeader(name = "userId") Long userId, + @PathVariable(name = "missionId") Long missionId, + @RequestBody @Valid ReviewRequestDto.CreateReviewDto request + ) { + Review review = reviewCommandService.createReview(userId, missionId, request); + + ReviewResponseDto.CreateReviewResultDto response = ReviewResponseDto.CreateReviewResultDto.builder() + .reviewId(review.getId()) + .createdAt(review.getCreatedAt()) + .build(); + + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } + + @GetMapping("/my") + public ApiResponse> getMyReviews( + @RequestHeader(name = "userId") Long userId, + @RequestParam(name = "cursor", defaultValue = "-1") String cursor, + @RequestParam(name = "query", defaultValue = "id") String query, + @RequestParam(name = "size", defaultValue = "10") Integer size + ) { + Slice reviewSlice = reviewQueryService.getMyReviews(userId, cursor, query, size); + + List data = reviewSlice.stream() + .map(r -> ReviewResponseDto.MyReviewDto.builder() + .reviewId(r.getId()) + .storeName(r.getStore().getName()) + .star(r.getStar()) + .content(r.getContent()) + .createdAt(r.getCreatedAt()) + .build()) + .collect(Collectors.toList()); + + String nextCursor = null; + if (reviewSlice.hasNext() && !data.isEmpty()) { + Review lastReview = reviewSlice.getContent().get(reviewSlice.getContent().size() - 1); + if (query.equalsIgnoreCase("star")) { + nextCursor = lastReview.getStar() + ":" + lastReview.getId(); + } else { + nextCursor = String.valueOf(lastReview.getId()); + } + } + + CursorResponseDto response = CursorResponseDto.builder() + .data(data) + .hasNext(reviewSlice.hasNext()) + .nextCursor(nextCursor) + .pageSize(reviewSlice.getSize()) + .build(); + + return ApiResponse.onSuccess(GeneralSuccessCode.OK, response); + } +} diff --git a/src/main/java/umc/domain/review/dto/.DS_Store b/src/main/java/umc/domain/review/dto/.DS_Store new file mode 100644 index 0000000..eb9ac1e Binary files /dev/null and b/src/main/java/umc/domain/review/dto/.DS_Store differ diff --git a/src/main/java/umc/domain/review/dto/request/ReviewRequestDto.java b/src/main/java/umc/domain/review/dto/request/ReviewRequestDto.java new file mode 100644 index 0000000..724676f --- /dev/null +++ b/src/main/java/umc/domain/review/dto/request/ReviewRequestDto.java @@ -0,0 +1,22 @@ +package umc.domain.review.dto.request; + +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import java.util.List; + +public class ReviewRequestDto { + + public record CreateReviewDto( + @NotNull(message = "별점은 필수입니다.") + @Min(value = 1, message = "최소 별점은 1점입니다. ") + @Max(value = 5, message = "최대 별점은 5점입니다. ") + Integer star, + + @NotBlank(message = "리뷰 내용은 필수입니다.") + String content, + + List image + ) {} +} \ No newline at end of file diff --git a/src/main/java/umc/domain/review/dto/response/ReviewResponseDto.java b/src/main/java/umc/domain/review/dto/response/ReviewResponseDto.java new file mode 100644 index 0000000..00f48d7 --- /dev/null +++ b/src/main/java/umc/domain/review/dto/response/ReviewResponseDto.java @@ -0,0 +1,33 @@ +package umc.domain.review.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import java.time.LocalDateTime; + +public class ReviewResponseDto { + + // 리뷰 생성 성공 시 응답 + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class CreateReviewResultDto { + private Long reviewId; + private LocalDateTime createdAt; + } + + // 내가 쓴 리뷰 조회 시 응답 + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MyReviewDto { + private Long reviewId; + private String storeName; + private Float star; + private String content; + private LocalDateTime createdAt; + } +} \ No newline at end of file diff --git a/src/main/java/umc/domain/review/entity/Review.java b/src/main/java/umc/domain/review/entity/Review.java new file mode 100644 index 0000000..a73253f --- /dev/null +++ b/src/main/java/umc/domain/review/entity/Review.java @@ -0,0 +1,35 @@ +package umc.domain.review.entity; + +import jakarta.persistence.*; +import lombok.*; +import umc.domain.mission.entity.Store; +import umc.domain.user.entity.User; +import umc.global.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class Review extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // 리뷰 내용 + private String content; + + // 별점 + private Float star; + + // 리뷰 작성 유저 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + // 리뷰가 작성된 가게 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id") + private Store store; +} \ No newline at end of file diff --git a/src/main/java/umc/domain/review/repository/ReviewRepository.java b/src/main/java/umc/domain/review/repository/ReviewRepository.java new file mode 100644 index 0000000..bc53636 --- /dev/null +++ b/src/main/java/umc/domain/review/repository/ReviewRepository.java @@ -0,0 +1,27 @@ +package umc.domain.review.repository; + +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Slice; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import umc.domain.review.entity.Review; + +public interface ReviewRepository extends JpaRepository { + + // ID 순 커서 페이징 + @Query("SELECT r FROM Review r JOIN FETCH r.store WHERE r.user.id = :userId AND r.id < :cursorId ORDER BY r.id DESC") + Slice findMyReviewsByIdCursor(@Param("userId") Long userId, @Param("cursorId") Long cursorId, PageRequest pageRequest); + + // ID 순 처음 조회(커서 없는 경우) + @Query("SELECT r FROM Review r JOIN FETCH r.store WHERE r.user.id = :userId ORDER BY r.id DESC") + Slice findMyReviewsOrderByIdDesc(@Param("userId") Long userId, PageRequest pageRequest); + + // 별점 순 커서 페이징(별점 같을시 ID 최신순) + @Query("SELECT r FROM Review r JOIN FETCH r.store WHERE r.user.id = :userId AND (r.star < :cursorStar OR (r.star = :cursorStar AND r.id < :cursorId)) ORDER BY r.star DESC, r.id DESC") + Slice findMyReviewsByStarCursor(@Param("userId") Long userId, @Param("cursorStar") Float cursorStar, @Param("cursorId") Long cursorId, PageRequest pageRequest); + + // 별점 순 처음 조회(커서 없는 경우) + @Query("SELECT r FROM Review r JOIN FETCH r.store WHERE r.user.id = :userId ORDER BY r.star DESC, r.id DESC") + Slice findMyReviewsOrderByStarDesc(@Param("userId") Long userId, PageRequest pageRequest); +} \ No newline at end of file diff --git a/src/main/java/umc/domain/review/service/ReviewCommandServiceImpl.java b/src/main/java/umc/domain/review/service/ReviewCommandServiceImpl.java new file mode 100644 index 0000000..e44d08f --- /dev/null +++ b/src/main/java/umc/domain/review/service/ReviewCommandServiceImpl.java @@ -0,0 +1,43 @@ +package umc.domain.review.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import umc.domain.mission.entity.Mission; +import umc.domain.mission.repository.MissionRepository; +import umc.domain.review.dto.request.ReviewRequestDto; +import umc.domain.review.entity.Review; +import umc.domain.review.repository.ReviewRepository; +import umc.domain.user.entity.User; +import umc.domain.user.repository.UserRepository; +import umc.global.apiPayload.code.status.GeneralErrorCode; +import umc.global.apiPayload.exception.ProjectException; + +@Service +@RequiredArgsConstructor +@Transactional +public class ReviewCommandServiceImpl { + + private final ReviewRepository reviewRepository; + private final UserRepository userRepository; + private final MissionRepository missionRepository; + + public Review createReview(Long userId, Long missionId, ReviewRequestDto.CreateReviewDto request) { + // 유저 찾기 + User user = userRepository.findById(userId) + .orElseThrow(() -> new ProjectException(GeneralErrorCode.NOT_FOUND)); + +// 미션 찾기 + Mission mission = missionRepository.findById(missionId) + .orElseThrow(() -> new ProjectException(GeneralErrorCode.NOT_FOUND)); + + Review review = Review.builder() + .user(user) + .store(mission.getStore()) + .star(request.star().floatValue()) + .content(request.content()) + .build(); + + return reviewRepository.save(review); + } +} \ No newline at end of file diff --git a/src/main/java/umc/domain/review/service/ReviewQueryServiceImpl.java b/src/main/java/umc/domain/review/service/ReviewQueryServiceImpl.java new file mode 100644 index 0000000..d01ae7d --- /dev/null +++ b/src/main/java/umc/domain/review/service/ReviewQueryServiceImpl.java @@ -0,0 +1,39 @@ +package umc.domain.review.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Slice; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import umc.domain.review.entity.Review; +import umc.domain.review.repository.ReviewRepository; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class ReviewQueryServiceImpl { + + private final ReviewRepository reviewRepository; + + public Slice getMyReviews(Long userId, String cursor, String query, Integer size) { + PageRequest pageRequest = PageRequest.of(0, size); + + if (query.equalsIgnoreCase("star")) { + if (cursor.equals("-1")) { + return reviewRepository.findMyReviewsOrderByStarDesc(userId, pageRequest); + } else { + String[] cursorSplit = cursor.split(":"); + Float cursorStar = Float.parseFloat(cursorSplit[0]); + Long cursorId = Long.parseLong(cursorSplit[1]); + return reviewRepository.findMyReviewsByStarCursor(userId, cursorStar, cursorId, pageRequest); + } + } else { + if (cursor.equals("-1")) { + return reviewRepository.findMyReviewsOrderByIdDesc(userId, pageRequest); + } else { + Long cursorId = Long.parseLong(cursor); + return reviewRepository.findMyReviewsByIdCursor(userId, cursorId, pageRequest); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/umc/domain/user/.DS_Store b/src/main/java/umc/domain/user/.DS_Store new file mode 100644 index 0000000..dc8af7f Binary files /dev/null and b/src/main/java/umc/domain/user/.DS_Store differ diff --git a/src/main/java/umc/domain/user/controller/UserController.java b/src/main/java/umc/domain/user/controller/UserController.java new file mode 100644 index 0000000..e3b6b00 --- /dev/null +++ b/src/main/java/umc/domain/user/controller/UserController.java @@ -0,0 +1,38 @@ +package umc.domain.user.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; +import umc.domain.user.dto.request.UserRequestDto; +import umc.domain.user.dto.response.UserResponseDto; +import umc.global.apiPayload.ApiResponse; +import umc.global.apiPayload.code.status.GeneralSuccessCode; + +import java.time.LocalDateTime; + + +@RestController +@RequiredArgsConstructor +public class UserController { + + // 회원가입 + @PostMapping("/auth/signup") + public ApiResponse signUp(@RequestBody UserRequestDto.SignUpDto request) { + UserResponseDto.SignUpResultDto dummyResponse = UserResponseDto.SignUpResultDto.builder() + .userId(1L) + .createdAt(LocalDateTime.now()) + .build(); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, dummyResponse); + } + + // 홈 화면 + @GetMapping("/home") + public ApiResponse getHome() { + UserResponseDto.HomeResultDto dummyResponse = UserResponseDto.HomeResultDto.builder() + .welcomeMessage("홈 화면") + .build(); + return ApiResponse.onSuccess(GeneralSuccessCode.OK, dummyResponse); + } +} diff --git a/src/main/java/umc/domain/user/dto/.DS_Store b/src/main/java/umc/domain/user/dto/.DS_Store new file mode 100644 index 0000000..cd82a65 Binary files /dev/null and b/src/main/java/umc/domain/user/dto/.DS_Store differ diff --git a/src/main/java/umc/domain/user/dto/request/UserRequestDto.java b/src/main/java/umc/domain/user/dto/request/UserRequestDto.java new file mode 100644 index 0000000..4ccc931 --- /dev/null +++ b/src/main/java/umc/domain/user/dto/request/UserRequestDto.java @@ -0,0 +1,13 @@ +package umc.domain.user.dto.request; + +import java.util.List; + +public class UserRequestDto { + public record SignUpDto( + String name, + String gender, + String birth, + String address, + List foodCategory + ) {} +} diff --git a/src/main/java/umc/domain/user/dto/response/UserResponseDto.java b/src/main/java/umc/domain/user/dto/response/UserResponseDto.java new file mode 100644 index 0000000..ecfaad0 --- /dev/null +++ b/src/main/java/umc/domain/user/dto/response/UserResponseDto.java @@ -0,0 +1,18 @@ +package umc.domain.user.dto.response; + +import lombok.Builder; + +import java.time.LocalDateTime; + +public class UserResponseDto { + @Builder + public record SignUpResultDto( + Long userId, + LocalDateTime createdAt + ) {} + + @Builder + public record HomeResultDto ( + String welcomeMessage + ) {} +} diff --git a/src/main/java/umc/domain/user/entity/Food.java b/src/main/java/umc/domain/user/entity/Food.java new file mode 100644 index 0000000..4fb281e --- /dev/null +++ b/src/main/java/umc/domain/user/entity/Food.java @@ -0,0 +1,4 @@ +package umc.domain.user.entity; + +public class Food { +} diff --git a/src/main/java/umc/domain/user/entity/User.java b/src/main/java/umc/domain/user/entity/User.java new file mode 100644 index 0000000..acf71f0 --- /dev/null +++ b/src/main/java/umc/domain/user/entity/User.java @@ -0,0 +1,21 @@ +package umc.domain.user.entity; + +import jakarta.persistence.*; +import lombok.*; +import umc.global.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class User extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 20) + private String name; + +} \ No newline at end of file diff --git a/src/main/java/umc/domain/user/entity/mapping/MissionStatus.java b/src/main/java/umc/domain/user/entity/mapping/MissionStatus.java new file mode 100644 index 0000000..18302ce --- /dev/null +++ b/src/main/java/umc/domain/user/entity/mapping/MissionStatus.java @@ -0,0 +1,5 @@ +package umc.domain.user.entity.mapping; + +public enum MissionStatus { + CHALLENGING, COMPLETE +} \ No newline at end of file diff --git a/src/main/java/umc/domain/user/entity/mapping/Preference.java b/src/main/java/umc/domain/user/entity/mapping/Preference.java new file mode 100644 index 0000000..5ca7f7d --- /dev/null +++ b/src/main/java/umc/domain/user/entity/mapping/Preference.java @@ -0,0 +1,4 @@ +package umc.domain.user.entity.mapping; + +public class Preference { +} diff --git a/src/main/java/umc/domain/user/entity/mapping/UserMission.java b/src/main/java/umc/domain/user/entity/mapping/UserMission.java new file mode 100644 index 0000000..f8dec73 --- /dev/null +++ b/src/main/java/umc/domain/user/entity/mapping/UserMission.java @@ -0,0 +1,31 @@ +package umc.domain.user.entity.mapping; + +import jakarta.persistence.*; +import lombok.*; +import umc.domain.mission.entity.Mission; +import umc.domain.user.entity.User; +import umc.global.common.BaseEntity; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class UserMission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + @Column(columnDefinition = "VARCHAR(15) DEFAULT 'CHALLENGING'") + private MissionStatus status; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "mission_id") + private Mission mission; +} \ No newline at end of file diff --git a/src/main/java/umc/domain/user/repository/UserRepository.java b/src/main/java/umc/domain/user/repository/UserRepository.java new file mode 100644 index 0000000..41fd69d --- /dev/null +++ b/src/main/java/umc/domain/user/repository/UserRepository.java @@ -0,0 +1,7 @@ +package umc.domain.user.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import umc.domain.user.entity.User; + +public interface UserRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/umc/global/.DS_Store b/src/main/java/umc/global/.DS_Store new file mode 100644 index 0000000..a1117cd Binary files /dev/null and b/src/main/java/umc/global/.DS_Store differ diff --git a/src/main/java/umc/global/apiPayload/ApiResponse.java b/src/main/java/umc/global/apiPayload/ApiResponse.java new file mode 100644 index 0000000..503ce06 --- /dev/null +++ b/src/main/java/umc/global/apiPayload/ApiResponse.java @@ -0,0 +1,41 @@ +package umc.global.apiPayload; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.AllArgsConstructor; +import lombok.Getter; +import umc.global.apiPayload.code.BaseErrorCode; +import umc.global.apiPayload.code.BaseSuccessCode; + +@Getter +@AllArgsConstructor +@JsonPropertyOrder({"isSuccess", "code", "message", "result"}) +public class ApiResponse { + + @JsonProperty("isSuccess") + private final Boolean isSuccess; + + @JsonProperty("code") + private final String code; + + @JsonProperty("message") + private final String message; + + @JsonProperty("result") + private T result; + + // 성공한 경우 응답 생성 + public static ApiResponse onSuccess(BaseSuccessCode code, T result) { + return new ApiResponse<>(true, code.getCode(), code.getMessage(), result); + } + + // 실패한 경우 응답 생성 + public static ApiResponse onFailure(BaseErrorCode code, T result) { + return new ApiResponse<>(false, code.getCode(), code.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/src/main/java/umc/global/apiPayload/code/BaseErrorCode.java b/src/main/java/umc/global/apiPayload/code/BaseErrorCode.java new file mode 100644 index 0000000..30dd696 --- /dev/null +++ b/src/main/java/umc/global/apiPayload/code/BaseErrorCode.java @@ -0,0 +1,9 @@ +package umc.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseErrorCode { + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} \ No newline at end of file diff --git a/src/main/java/umc/global/apiPayload/code/BaseSuccessCode.java b/src/main/java/umc/global/apiPayload/code/BaseSuccessCode.java new file mode 100644 index 0000000..e68f198 --- /dev/null +++ b/src/main/java/umc/global/apiPayload/code/BaseSuccessCode.java @@ -0,0 +1,9 @@ +package umc.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseSuccessCode { + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} \ No newline at end of file diff --git a/src/main/java/umc/global/apiPayload/code/status/GeneralErrorCode.java b/src/main/java/umc/global/apiPayload/code/status/GeneralErrorCode.java new file mode 100644 index 0000000..3858f15 --- /dev/null +++ b/src/main/java/umc/global/apiPayload/code/status/GeneralErrorCode.java @@ -0,0 +1,21 @@ +package umc.global.apiPayload.code.status; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import umc.global.apiPayload.code.BaseErrorCode; + +@Getter +@RequiredArgsConstructor +public enum GeneralErrorCode implements BaseErrorCode { + + BAD_REQUEST(HttpStatus.BAD_REQUEST, "COMMON400_1", "잘못된 요청입니다."), + UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "COMMON401_1", "인증되지 않았습니다."), + FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON403_1", "접근이 금지되었습니다."), + NOT_FOUND(HttpStatus.NOT_FOUND, "COMMON404_1", "해당 리소스를 찾을 수 없습니다."), + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON500_1", "서버 에러가 발생했습니다."); + + private final HttpStatus status; + private final String code; + private final String message; +} \ No newline at end of file diff --git a/src/main/java/umc/global/apiPayload/code/status/GeneralSuccessCode.java b/src/main/java/umc/global/apiPayload/code/status/GeneralSuccessCode.java new file mode 100644 index 0000000..48856b6 --- /dev/null +++ b/src/main/java/umc/global/apiPayload/code/status/GeneralSuccessCode.java @@ -0,0 +1,17 @@ +package umc.global.apiPayload.code.status; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import umc.global.apiPayload.code.BaseSuccessCode; + +@Getter +@RequiredArgsConstructor +public enum GeneralSuccessCode implements BaseSuccessCode { + + OK(HttpStatus.OK, "COMMON200_1", "요청 처리 성공"); + + private final HttpStatus status; + private final String code; + private final String message; +} \ No newline at end of file diff --git a/src/main/java/umc/global/apiPayload/exception/ProjectException.java b/src/main/java/umc/global/apiPayload/exception/ProjectException.java new file mode 100644 index 0000000..7004d70 --- /dev/null +++ b/src/main/java/umc/global/apiPayload/exception/ProjectException.java @@ -0,0 +1,12 @@ +package umc.global.apiPayload.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import umc.global.apiPayload.code.BaseErrorCode; + +@Getter +@RequiredArgsConstructor +public class ProjectException extends RuntimeException { + + private final BaseErrorCode errorCode; +} \ No newline at end of file diff --git a/src/main/java/umc/global/apiPayload/exception/handler/GeneralExceptionAdvice.java b/src/main/java/umc/global/apiPayload/exception/handler/GeneralExceptionAdvice.java new file mode 100644 index 0000000..cb85cd9 --- /dev/null +++ b/src/main/java/umc/global/apiPayload/exception/handler/GeneralExceptionAdvice.java @@ -0,0 +1,47 @@ +package umc.global.apiPayload.exception.handler; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import umc.global.apiPayload.ApiResponse; +import umc.global.apiPayload.code.BaseErrorCode; +import umc.global.apiPayload.code.status.GeneralErrorCode; +import umc.global.apiPayload.exception.ProjectException; + +import java.util.LinkedHashMap; +import java.util.Map; + +@RestControllerAdvice +public class GeneralExceptionAdvice { + + @ExceptionHandler(ProjectException.class) + public ResponseEntity> handleProjectException(ProjectException e) { + BaseErrorCode errorCode = e.getErrorCode(); + return ResponseEntity.status(errorCode.getStatus()) + .body(ApiResponse.onFailure(errorCode, null)); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> handleException(Exception ex) { + BaseErrorCode code = GeneralErrorCode.INTERNAL_SERVER_ERROR; + return ResponseEntity.status(code.getStatus()) + .body(ApiResponse.onFailure(code, ex.getMessage())); + } + + // Valid 검증 실패 시 예외처리 + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException e) { + Map errors = new LinkedHashMap<>(); + + e.getBindingResult().getFieldErrors().forEach(fieldError -> { + String fieldName = fieldError.getField(); + String errorMessage = fieldError.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body(ApiResponse.onFailure(GeneralErrorCode.BAD_REQUEST.getCode(), "잘못된 요청입니다.", errors)); + } +} \ No newline at end of file diff --git a/src/main/java/umc/global/common/BaseEntity.java b/src/main/java/umc/global/common/BaseEntity.java new file mode 100644 index 0000000..fe44757 --- /dev/null +++ b/src/main/java/umc/global/common/BaseEntity.java @@ -0,0 +1,22 @@ +package umc.global.common; + +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@Getter +public abstract class BaseEntity { + + @CreatedDate + private LocalDateTime createdAt; + + @LastModifiedDate + private LocalDateTime updatedAt; +} \ No newline at end of file diff --git a/src/main/java/umc/global/common/CursorResponseDto.java b/src/main/java/umc/global/common/CursorResponseDto.java new file mode 100644 index 0000000..1f978e2 --- /dev/null +++ b/src/main/java/umc/global/common/CursorResponseDto.java @@ -0,0 +1,18 @@ +package umc.global.common; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import java.util.List; + +@Builder +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class CursorResponseDto { + private List data; + private Boolean hasNext; + private String nextCursor; + private Integer pageSize; +} \ No newline at end of file diff --git a/src/main/java/umc/global/common/PageResponseDto.java b/src/main/java/umc/global/common/PageResponseDto.java new file mode 100644 index 0000000..ac71ee4 --- /dev/null +++ b/src/main/java/umc/global/common/PageResponseDto.java @@ -0,0 +1,20 @@ +package umc.global.common; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import java.util.List; + +@Builder +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class PageResponseDto { + private List data; + private Integer listSize; + private Integer totalPage; + private Long totalElements; + private Boolean isFirst; + private Boolean isLast; +} \ No newline at end of file diff --git a/src/main/java/umc/global/config/SecurityConfig.java b/src/main/java/umc/global/config/SecurityConfig.java new file mode 100644 index 0000000..1dbfcb7 --- /dev/null +++ b/src/main/java/umc/global/config/SecurityConfig.java @@ -0,0 +1,24 @@ +package umc.global.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf(csrf -> csrf.disable()) // CSRF 보호 비활성화 (테스트용) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() // Swagger 경로는 누구나 접근 가능 + .anyRequest().permitAll() // 일단 지금은 모든 API 요청을 로그인 없이 열어두기 (9주차에 수정 예정) + ); + return http.build(); + } + +} \ No newline at end of file diff --git a/src/main/java/umc/global/config/SwaggerConfig.java b/src/main/java/umc/global/config/SwaggerConfig.java new file mode 100644 index 0000000..d128424 --- /dev/null +++ b/src/main/java/umc/global/config/SwaggerConfig.java @@ -0,0 +1,19 @@ +package umc.global.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { + @Bean + public OpenAPI swagger() { + Info info = new Info().title("UMC10th API").description("UMC 10기 미션 API 명세서").version("0.0.1"); + + return new OpenAPI() + .components(new Components()) + .info(info); + } +} \ No newline at end of file diff --git a/src/test/java/umc/UmcApplicationTests.java b/src/test/java/umc/UmcApplicationTests.java new file mode 100644 index 0000000..47308f6 --- /dev/null +++ b/src/test/java/umc/UmcApplicationTests.java @@ -0,0 +1,13 @@ +package umc; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class UmcApplicationTests { + + @Test + void contextLoads() { + } + +}