diff --git a/.github/workflows/ci-cd-recruitment-service.yml b/.github/workflows/ci-cd-recruitment-service.yml index e288ae8..b217e01 100644 --- a/.github/workflows/ci-cd-recruitment-service.yml +++ b/.github/workflows/ci-cd-recruitment-service.yml @@ -10,14 +10,14 @@ env: SERVICE_NAME: recruitment-service # 예: order-service DOCKER_IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/${{ vars.DOCKER_IMAGE_NAME }}:latest EC2_HOST: ${{ secrets.EC2_HOST }} - EC2_SSH_USER: ec2-user + EC2_SSH_USER: kmj02dev PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} TIMEZONE: Asia/Seoul DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} PROJECT_PATH: /home/ec2-user/delivery-system/recruitment-service # 예: /home/ec2-user/delivery-system/order-service APPLICATION: ${{ secrets.APPLICATION }} - + jobs: build-and-push: runs-on: ubuntu-latest diff --git a/recruitment-service/.gitattributes b/recruitment-service/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/recruitment-service/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/recruitment-service/.github/workflows/ci-cd-order-service.yml b/recruitment-service/.github/workflows/ci-cd-order-service.yml new file mode 100644 index 0000000..35f0b82 --- /dev/null +++ b/recruitment-service/.github/workflows/ci-cd-order-service.yml @@ -0,0 +1,71 @@ +name: CI/CD for Spring Boot + MySQL with Docker Compose + +on: + push: + branches: [ "main", "order-service/main" ] + pull_request: + branches: [ "main", "order-service/main" ] + +env: + SERVICE_NAME: order-service # 예: order-service + DOCKER_IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/${{ vars.DOCKER_IMAGE_NAME }}:latest + EC2_HOST: ${{ secrets.EC2_HOST }} + EC2_SSH_USER: ec2-user + PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} + TIMEZONE: Asia/Seoul + DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + PROJECT_PATH: /home/ec2-user/delivery-system/order-service # 예: /home/ec2-user/delivery-system/order-service + +jobs: + build-and-push: + runs-on: ubuntu-latest + environment: order-service + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Grant execute permission for gradlew + run: chmod +x ${{ env.SERVICE_NAME }}/gradlew + + - name: Build Spring Boot Application + working-directory: ${{ env.SERVICE_NAME }} + run: ./gradlew build + + - name: Log in to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ env.DOCKER_USERNAME }} + password: ${{ env.DOCKER_TOKEN }} + + - name: Build Docker Image + run: docker build -t ${{ env.DOCKER_IMAGE }} ./${{ env.SERVICE_NAME }} + + - name: Push Docker Image + run: docker push ${{ env.DOCKER_IMAGE }} + + deploy-to-ec2: + runs-on: ubuntu-latest + if: github.event_name == 'push' + needs: build-and-push + environment: order-service + + steps: + - name: Deploy to EC2 via SSH + uses: appleboy/ssh-action@v0.1.6 + with: + host: ${{ env.EC2_HOST }} + username: ${{ env.EC2_SSH_USER }} + key: ${{ env.PRIVATE_KEY }} + script: | + cd ${{ env.PROJECT_PATH }} + sudo docker compose pull + sudo docker compose down + sudo docker compose up -d diff --git a/recruitment-service/.github/workflows/ci-cd-payment-service.yml b/recruitment-service/.github/workflows/ci-cd-payment-service.yml new file mode 100644 index 0000000..77e98a4 --- /dev/null +++ b/recruitment-service/.github/workflows/ci-cd-payment-service.yml @@ -0,0 +1,71 @@ +name: CI/CD for Spring Boot + MySQL with Docker Compose + +on: + push: + branches: [ "main", "payment-service/main" ] + pull_request: + branches: [ "main", "payment-service/main" ] + +env: + SERVICE_NAME: payment-service # 예: order-service + DOCKER_IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/${{ vars.DOCKER_IMAGE_NAME }}:latest + EC2_HOST: ${{ secrets.EC2_HOST }} + EC2_SSH_USER: ec2-user + PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} + TIMEZONE: Asia/Seoul + DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + PROJECT_PATH: /home/ec2-user/delivery-system/payment-service # 예: /home/ec2-user/delivery-system/order-service + +jobs: + build-and-push: + runs-on: ubuntu-latest + environment: payment-service + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Grant execute permission for gradlew + run: chmod +x ${{ env.SERVICE_NAME }}/gradlew + + - name: Build Spring Boot Application + working-directory: ${{ env.SERVICE_NAME }} + run: ./gradlew build + + - name: Log in to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ env.DOCKER_USERNAME }} + password: ${{ env.DOCKER_TOKEN }} + + - name: Build Docker Image + run: docker build -t ${{ env.DOCKER_IMAGE }} ./${{ env.SERVICE_NAME }} + + - name: Push Docker Image + run: docker push ${{ env.DOCKER_IMAGE }} + + deploy-to-ec2: + runs-on: ubuntu-latest + if: github.event_name == 'push' + needs: build-and-push + environment: payment-service + + steps: + - name: Deploy to EC2 via SSH + uses: appleboy/ssh-action@v0.1.6 + with: + host: ${{ env.EC2_HOST }} + username: ${{ env.EC2_SSH_USER }} + key: ${{ env.PRIVATE_KEY }} + script: | + cd ${{ env.PROJECT_PATH }} + sudo docker compose pull + sudo docker compose down + sudo docker compose up -d diff --git a/recruitment-service/.github/workflows/ci-cd-recruitment-service.yml b/recruitment-service/.github/workflows/ci-cd-recruitment-service.yml new file mode 100644 index 0000000..c457072 --- /dev/null +++ b/recruitment-service/.github/workflows/ci-cd-recruitment-service.yml @@ -0,0 +1,77 @@ +name: CI/CD for Spring Boot + MySQL with Docker Compose + +on: + push: + branches: [ "main", "recruitment-service/main" ] + pull_request: + branches: [ "main", "recruitment-service/main" ] + +env: + SERVICE_NAME: recruitment-service # 예: order-service + DOCKER_IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/${{ vars.DOCKER_IMAGE_NAME }}:latest + EC2_HOST: ${{ secrets.EC2_HOST }} + EC2_SSH_USER: ec2-user + PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} + TIMEZONE: Asia/Seoul + DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + PROJECT_PATH: /home/kmj02dev/delivery-system/recruitment-service # 예: /home/ec2-user/delivery-system/order-service + APPLICATION: ${{ secrets.APPLICATION }} + +jobs: + build-and-push: + runs-on: ubuntu-latest + environment: recruitment-service + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Set up application.properties + run : | + mkdir -p "${{ env.SERVICE_NAME }}"/src/main/resources + echo "${{ env.APPLICATION }}" > "${{ env.SERVICE_NAME }}/src/main/resources/application.properties" + + - name: Grant execute permission for gradlew + run: chmod +x ${{ env.SERVICE_NAME }}/gradlew + + - name: Build Spring Boot Application + working-directory: ${{ env.SERVICE_NAME }} + run: ./gradlew build + + - name: Log in to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ env.DOCKER_USERNAME }} + password: ${{ env.DOCKER_TOKEN }} + + - name: Build Docker Image + run: docker build -t ${{ env.DOCKER_IMAGE }} ./${{ env.SERVICE_NAME }} + + - name: Push Docker Image + run: docker push ${{ env.DOCKER_IMAGE }} + + deploy-to-ec2: + runs-on: ubuntu-latest + if: github.event_name == 'push' + needs: build-and-push + environment: recruitment-service + + steps: + - name: Deploy to EC2 via SSH + uses: appleboy/ssh-action@v0.1.6 + with: + host: ${{ env.EC2_HOST }} + username: ${{ env.EC2_SSH_USER }} + key: ${{ env.PRIVATE_KEY }} + script: | + cd ${{ env.PROJECT_PATH }} + sudo docker compose pull + sudo docker compose down + sudo docker compose up -d diff --git a/recruitment-service/.github/workflows/ci-cd-store-service.yml b/recruitment-service/.github/workflows/ci-cd-store-service.yml new file mode 100644 index 0000000..2c192b9 --- /dev/null +++ b/recruitment-service/.github/workflows/ci-cd-store-service.yml @@ -0,0 +1,71 @@ +name: CI/CD for Spring Boot + MySQL with Docker Compose + +on: + push: + branches: [ "main", "store-service/main" ] + pull_request: + branches: [ "main", "store-service/main" ] + +env: + SERVICE_NAME: store-service # 예: order-service + DOCKER_IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/${{ vars.DOCKER_IMAGE_NAME }}:latest + EC2_HOST: ${{ secrets.EC2_HOST }} + EC2_SSH_USER: ec2-user + PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} + TIMEZONE: Asia/Seoul + DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + PROJECT_PATH: /home/ec2-user/delivery-system/store-service # 예: /home/ec2-user/delivery-system/order-service + +jobs: + build-and-push: + runs-on: ubuntu-latest + environment: store-service + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Grant execute permission for gradlew + run: chmod +x ${{ env.SERVICE_NAME }}/gradlew + + - name: Build Spring Boot Application + working-directory: ${{ env.SERVICE_NAME }} + run: ./gradlew build + + - name: Log in to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ env.DOCKER_USERNAME }} + password: ${{ env.DOCKER_TOKEN }} + + - name: Build Docker Image + run: docker build -t ${{ env.DOCKER_IMAGE }} ./${{ env.SERVICE_NAME }} + + - name: Push Docker Image + run: docker push ${{ env.DOCKER_IMAGE }} + + deploy-to-ec2: + runs-on: ubuntu-latest + if: github.event_name == 'push' + needs: build-and-push + environment: store-service + + steps: + - name: Deploy to EC2 via SSH + uses: appleboy/ssh-action@v0.1.6 + with: + host: ${{ env.EC2_HOST }} + username: ${{ env.EC2_SSH_USER }} + key: ${{ env.PRIVATE_KEY }} + script: | + cd ${{ env.PROJECT_PATH }} + sudo docker compose pull + sudo docker compose down + sudo docker compose up -d diff --git a/recruitment-service/.github/workflows/ci-cd-user-service.yml b/recruitment-service/.github/workflows/ci-cd-user-service.yml new file mode 100644 index 0000000..48c2839 --- /dev/null +++ b/recruitment-service/.github/workflows/ci-cd-user-service.yml @@ -0,0 +1,71 @@ +name: CI/CD for Spring Boot + MySQL with Docker Compose + +on: + push: + branches: [ "main", "user-service/main" ] + pull_request: + branches: [ "main", "user-service/main" ] + +env: + SERVICE_NAME: user-service # 예: order-service + DOCKER_IMAGE: ${{ secrets.DOCKERHUB_USERNAME }}/${{ vars.DOCKER_IMAGE_NAME }}:latest + EC2_HOST: ${{ secrets.EC2_HOST }} + EC2_SSH_USER: ec2-user + PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} + TIMEZONE: Asia/Seoul + DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + PROJECT_PATH: /home/ec2-user/delivery-system/user-service # 예: /home/ec2-user/delivery-system/order-service + +jobs: + build-and-push: + runs-on: ubuntu-latest + environment: user-service + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Grant execute permission for gradlew + run: chmod +x ${{ env.SERVICE_NAME }}/gradlew + + - name: Build Spring Boot Application + working-directory: ${{ env.SERVICE_NAME }} + run: ./gradlew build + + - name: Log in to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ env.DOCKER_USERNAME }} + password: ${{ env.DOCKER_TOKEN }} + + - name: Build Docker Image + run: docker build -t ${{ env.DOCKER_IMAGE }} ./${{ env.SERVICE_NAME }} + + - name: Push Docker Image + run: docker push ${{ env.DOCKER_IMAGE }} + + deploy-to-ec2: + runs-on: ubuntu-latest + if: github.event_name == 'push' + needs: build-and-push + environment: user-service + + steps: + - name: Deploy to EC2 via SSH + uses: appleboy/ssh-action@v0.1.6 + with: + host: ${{ env.EC2_HOST }} + username: ${{ env.EC2_SSH_USER }} + key: ${{ env.PRIVATE_KEY }} + script: | + cd ${{ env.PROJECT_PATH }} + sudo docker compose pull + sudo docker compose down + sudo docker compose up -d diff --git a/recruitment-service/.gitignore b/recruitment-service/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/recruitment-service/.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/recruitment-service/build.gradle b/recruitment-service/build.gradle new file mode 100644 index 0000000..176a78b --- /dev/null +++ b/recruitment-service/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.5' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'com.h2database:h2' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/recruitment-service/gradle/wrapper/gradle-wrapper.jar b/recruitment-service/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9bbc975 Binary files /dev/null and b/recruitment-service/gradle/wrapper/gradle-wrapper.jar differ diff --git a/recruitment-service/gradle/wrapper/gradle-wrapper.properties b/recruitment-service/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/recruitment-service/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/recruitment-service/gradlew b/recruitment-service/gradlew new file mode 100644 index 0000000..58fb3e1 --- /dev/null +++ b/recruitment-service/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=$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, 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/recruitment-service/gradlew.bat b/recruitment-service/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/recruitment-service/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/recruitment-service/settings.gradle b/recruitment-service/settings.gradle new file mode 100644 index 0000000..ea4147d --- /dev/null +++ b/recruitment-service/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'recruitment' diff --git a/recruitment-service/src/main/java/com/example/recruitment/RecruitmentApplication.java b/recruitment-service/src/main/java/com/example/recruitment/RecruitmentApplication.java new file mode 100644 index 0000000..88d3cf6 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/RecruitmentApplication.java @@ -0,0 +1,13 @@ +package com.example.recruitment; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RecruitmentApplication { + + public static void main(String[] args) { + SpringApplication.run(RecruitmentApplication.class, args); + } + +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/RecruitmentControllerTest.java b/recruitment-service/src/main/java/com/example/recruitment/RecruitmentControllerTest.java new file mode 100644 index 0000000..4ec5f43 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/RecruitmentControllerTest.java @@ -0,0 +1,13 @@ +package com.example.recruitment; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RecruitmentControllerTest { + + @GetMapping("/") + public String hello() { + return "서버 정상 작동 중!"; + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/common/ApiResponse.java b/recruitment-service/src/main/java/com/example/recruitment/common/ApiResponse.java new file mode 100644 index 0000000..e4938a4 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/common/ApiResponse.java @@ -0,0 +1,32 @@ +package com.example.recruitment.common; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.springframework.http.HttpStatus; + +import java.util.List; + +public record ApiResponse( + @JsonIgnore HttpStatus httpStatus, + boolean isSuccess, + int code, + String message, + T data, + List errors +) { + public static ApiResponse ok(T data, String message) { + return new ApiResponse<>(HttpStatus.OK, true, 1000, message, data, null); + } + + public static ApiResponse created(T data, String message) { + return new ApiResponse<>(HttpStatus.CREATED, true, 1001, message, data, null); + } + + public static ApiResponse fail(int code, String message, HttpStatus status) { + return new ApiResponse<>(status, false, code, message, null, null); + } + + public static ApiResponse validationFail(List errors) { + return new ApiResponse<>(HttpStatus.BAD_REQUEST, false, 2001, "입력 값 유효성 검사 실패", null, errors); + } +} + diff --git a/recruitment-service/src/main/java/com/example/recruitment/common/FieldErrorDetail.java b/recruitment-service/src/main/java/com/example/recruitment/common/FieldErrorDetail.java new file mode 100644 index 0000000..cbc295d --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/common/FieldErrorDetail.java @@ -0,0 +1,11 @@ +package com.example.recruitment.common; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class FieldErrorDetail { + private String field; + private String reason; +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java b/recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java new file mode 100644 index 0000000..9e15016 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java @@ -0,0 +1,168 @@ +package com.example.recruitment.controller; + +import com.example.recruitment.dto.RecruitmentDetailDto; +import com.example.recruitment.dto.RecruitmentRequestDto; +import com.example.recruitment.dto.order.OrderRequestDto; +import com.example.recruitment.entity.Recruitment; +import com.example.recruitment.entity.RecruitmentParticipant; +import com.example.recruitment.entity.User; +import com.example.recruitment.repository.RecruitmentParticipantRepository; +import com.example.recruitment.repository.RecruitmentRepository; +import com.example.recruitment.service.RecruitmentService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDateTime; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/recruitments") +public class RecruitmentController { + + private final RecruitmentService recruitmentService; + private final RecruitmentRepository recruitmentRepository; + private final RecruitmentParticipantRepository participantRepository; + + //모집글 생성 (Order 서버에 주문 생성 포함) + @PostMapping + public ResponseEntity createRecruitment(@Valid @RequestBody RecruitmentRequestDto dto) { + recruitmentService.createRecruitment(dto); + return ResponseEntity.ok("모집글 생성 완료"); + } + + //모집글 참여 (Order 서버에 주문 생성 포함) + @PostMapping("/{recruitmentId}/join") + public ResponseEntity joinRecruitment(@PathVariable Long recruitmentId, + @RequestParam Long userId, + @RequestBody OrderRequestDto orderRequestDto) { + recruitmentService.joinRecruitment(recruitmentId, userId, orderRequestDto); + return ResponseEntity.ok("모집글 참여 완료"); + } + + // 모집글 전체 조회 + @GetMapping + public List getAll() { + return recruitmentRepository.findAll(); + } + + // 상태별 조회 + @GetMapping(params = "status") + public List getByStatus(@RequestParam String status) { + return recruitmentRepository.findByStatus(status); + } + + // 모집글 상세 조회 + @GetMapping("/{recruitmentId}") + public ResponseEntity getRecruitmentDetail(@PathVariable Long recruitmentId) { + Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow(); + + List participants = + participantRepository.findByRecruitmentId(recruitmentId); + List participantUsers = participants.stream() + .map(RecruitmentParticipant::getUser) + .toList(); + + RecruitmentDetailDto dto = new RecruitmentDetailDto(); + dto.setId(recruitment.getId()); + dto.setTitle(recruitment.getTitle()); + dto.setDescription(recruitment.getDescription()); + dto.setStatus(recruitment.getStatus()); + dto.setDeadlineTime(recruitment.getDeadlineTime()); + dto.setUser(recruitment.getUser()); + dto.setStore(recruitment.getStore()); + dto.setParticipants(participantUsers); + + return ResponseEntity.ok(dto); + } + + // 유저가 만든 모집글 + @GetMapping("/user/{userId}/created-recruitments") + public List getRecruitmentsCreatedByUser(@PathVariable Long userId) { + return recruitmentRepository.findByUserId(userId); + } + + // 유저가 참여한 모집글 + @GetMapping("/user/{userId}/joined-recruitments") + public List getRecruitmentsJoinedByUser(@PathVariable Long userId) { + List participantList = participantRepository.findByUserId(userId); + return participantList.stream() + .map(RecruitmentParticipant::getRecruitment) + .toList(); + } + + // 모집 상태 업데이트 + @PatchMapping("/{recruitmentId}/status") + public ResponseEntity updateRecruitmentStatus(@PathVariable Long recruitmentId) { + Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow(); + LocalDateTime now = LocalDateTime.now(); + long participantCount = participantRepository.countByRecruitmentId(recruitmentId); + + if (now.isAfter(recruitment.getDeadlineTime())) { + if (participantCount >= 3) { + recruitment.setStatus("CONFIRMED"); + } else { + recruitment.setStatus("FAILED"); + } + recruitmentRepository.save(recruitment); + return ResponseEntity.ok("상태가 " + recruitment.getStatus() + "로 변경되었습니다."); + } else { + return ResponseEntity.ok("아직 마감 시간이 지나지 않았습니다."); + } + } + + // 주문 수락 상태 변경 + @PatchMapping("/{recruitmentId}/accept") + public ResponseEntity acceptRecruitment(@PathVariable Long recruitmentId) { + Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow(); + if (!"CONFIRMED".equals(recruitment.getStatus())) { + return ResponseEntity.badRequest().body("주문 수락은 CONFIRMED 상태에서만 가능합니다."); + } + recruitment.setStatus("ACCEPTED"); + recruitmentRepository.save(recruitment); + return ResponseEntity.ok("상태가 ACCEPTED로 변경되었습니다."); + } + + // 배달 완료 상태 변경 + @PatchMapping("/{recruitmentId}/deliver") + public ResponseEntity completeDelivery(@PathVariable Long recruitmentId) { + Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow(); + if (!"ACCEPTED".equals(recruitment.getStatus())) { + return ResponseEntity.badRequest().body("배달 완료는 ACCEPTED 상태에서만 가능합니다."); + } + recruitment.setStatus("DELIVERED"); + recruitmentRepository.save(recruitment); + return ResponseEntity.ok("상태가 DELIVERED로 변경되었습니다."); + } + + // 모집글 삭제 + @DeleteMapping("/{recruitmentId}") + public ResponseEntity deleteRecruitment(@PathVariable Long recruitmentId) { + Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow(); + recruitmentRepository.delete(recruitment); + return ResponseEntity.ok("모집글이 삭제되었습니다."); + } + + // 모집글 수정 + @PutMapping("/{recruitmentId}") + public ResponseEntity updateRecruitment(@PathVariable Long recruitmentId, + @Valid @RequestBody RecruitmentRequestDto dto) { + Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow(); + if (!recruitment.getUser().getId().equals(dto.getUserId())) { + return ResponseEntity.status(403).body("작성자만 수정할 수 있습니다."); + } + + recruitment.setTitle(dto.getTitle()); + recruitment.setDescription(dto.getDescription()); + recruitment.setDeadlineTime(dto.getDeadlineTime()); + + if (dto.getStoreId() != null) { + recruitment.setStore(recruitment.getStore()); + } + + recruitmentRepository.save(recruitment); + return ResponseEntity.ok("모집글이 수정되었습니다."); + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/controller/StoreController.java b/recruitment-service/src/main/java/com/example/recruitment/controller/StoreController.java new file mode 100644 index 0000000..64f35a4 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/controller/StoreController.java @@ -0,0 +1,28 @@ +package com.example.recruitment.controller; + +import com.example.recruitment.entity.Store; +import com.example.recruitment.repository.StoreRepository; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/stores") +public class StoreController { + + private final StoreRepository storeRepository; + + @PostMapping + public Store createStore(@Valid @RequestBody Store store) { + return storeRepository.save(store); + } + + @GetMapping + public List getAllStores() { + return storeRepository.findAll(); + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/controller/SwaggerTestController.java b/recruitment-service/src/main/java/com/example/recruitment/controller/SwaggerTestController.java new file mode 100644 index 0000000..ec9233a --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/controller/SwaggerTestController.java @@ -0,0 +1,14 @@ +package com.example.recruitment.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/swagger-test") +public class SwaggerTestController { + @GetMapping + public String test() { + return "Swagger works!"; + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/controller/UserController.java b/recruitment-service/src/main/java/com/example/recruitment/controller/UserController.java new file mode 100644 index 0000000..f34c042 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/controller/UserController.java @@ -0,0 +1,28 @@ +package com.example.recruitment.controller; + +import com.example.recruitment.entity.User; +import com.example.recruitment.repository.UserRepository; + +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/users") +public class UserController { + + private final UserRepository userRepository; + + @PostMapping + public User createUser(@Valid @RequestBody User user) { + return userRepository.save(user); + } + + @GetMapping + public List getAllUsers() { + return userRepository.findAll(); + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java b/recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java new file mode 100644 index 0000000..258a3d3 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java @@ -0,0 +1,21 @@ +package com.example.recruitment.dto; + +import com.example.recruitment.entity.Store; +import com.example.recruitment.entity.User; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; +import java.util.List; + +@Getter @Setter +public class RecruitmentDetailDto { + private Long id; + private String title; + private String description; + private String status; + private LocalDateTime deadlineTime; + private User user; + private Store store; + private List participants; +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentRequestDto.java b/recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentRequestDto.java new file mode 100644 index 0000000..a97aa2c --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentRequestDto.java @@ -0,0 +1,46 @@ +package com.example.recruitment.dto; + +import com.example.recruitment.dto.order.OrderRequestDto; +import lombok.Getter; +import lombok.Setter; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.time.LocalDateTime; +import java.util.List; + +@Getter +@Setter +public class RecruitmentRequestDto { + + @NotNull(message = "userId는 필수입니다.") + private Long userId; + + @NotNull(message = "storeId는 필수입니다.") + private Long storeId; + + @NotBlank(message = "제목은 비어 있을 수 없습니다.") + private String title; + + @Size(min = 10, message = "설명은 최소 10자 이상이어야 합니다.") + private String description; + + @NotNull(message = "마감 시간은 필수입니다.") + private LocalDateTime deadlineTime; + + @NotBlank(message = "카테고리는 비어 있을 수 없습니다.") + private String category; + + // 주문용 메뉴 정보 + private List menus; + + //OrderRequestDto 변환 메서드 + public OrderRequestDto toOrderRequestDto() { + OrderRequestDto dto = new OrderRequestDto(); + dto.setUserId(this.userId); + dto.setStoreId(this.storeId); + dto.setMenus(this.menus); + return dto; + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderRequestDto.java b/recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderRequestDto.java new file mode 100644 index 0000000..c948a2f --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderRequestDto.java @@ -0,0 +1,32 @@ +package com.example.recruitment.dto.order; + +import java.util.List; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter + +public class OrderRequestDto { + private Long groupId; + private Long userId; + private Long storeId; + private List menus; + + @Getter @Setter + public static class MenuDto { + private Long menuId; + private String menuName; + private int basePrice; + private int count; + private List options; + } + + @Getter @Setter + public static class OptionDto { + private Long optionId; + private String optionName; + private int price; + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderResponseDto.java b/recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderResponseDto.java new file mode 100644 index 0000000..c5e64b9 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderResponseDto.java @@ -0,0 +1,10 @@ +package com.example.recruitment.dto.order; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class OrderResponseDto { + private Long orderId; +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/entity/Recruitment.java b/recruitment-service/src/main/java/com/example/recruitment/entity/Recruitment.java new file mode 100644 index 0000000..6c1b1ff --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/entity/Recruitment.java @@ -0,0 +1,49 @@ +package com.example.recruitment.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter @Setter +@NoArgsConstructor +@AllArgsConstructor +public class Recruitment { + + @Id @GeneratedValue + private Long id; + + @ManyToOne + private User user; + + @ManyToOne + private Store store; + + @OneToMany(mappedBy = "recruitment", cascade = CascadeType.ALL, orphanRemoval = true) + private List participants; + + private String title; + private String description; + + private String status; // RECRUITING, CONFIRMED 등 + + private LocalDateTime deadlineTime; + + //카테고리 추가가 + @Column(nullable = false) + private String category; + + @Column(name = "order_id") + private Long orderId; + + @ElementCollection + private List orderIds = new ArrayList<>(); + + public void addOrderId(Long orderId) { + this.orderIds.add(orderId); +} + +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/entity/RecruitmentParticipant.java b/recruitment-service/src/main/java/com/example/recruitment/entity/RecruitmentParticipant.java new file mode 100644 index 0000000..23b03cd --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/entity/RecruitmentParticipant.java @@ -0,0 +1,33 @@ +package com.example.recruitment.entity; + +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; + +@Entity +@Getter @Setter +@NoArgsConstructor +@AllArgsConstructor +public class RecruitmentParticipant { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + + @ManyToOne + @JoinColumn(name = "user_id", nullable = false) + private User user; + + @ManyToOne + @JoinColumn(name = "recruitment_id", nullable = false) + private Recruitment recruitment; + + @Column(name = "joined_at", nullable = false) + private LocalDateTime joinedAt; + + @Column(name = "order_id") + private Long orderId; +} + diff --git a/recruitment-service/src/main/java/com/example/recruitment/entity/Store.java b/recruitment-service/src/main/java/com/example/recruitment/entity/Store.java new file mode 100644 index 0000000..0764630 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/entity/Store.java @@ -0,0 +1,18 @@ +package com.example.recruitment.entity; + +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Getter @Setter +@NoArgsConstructor +@AllArgsConstructor +public class Store { + + @Id @GeneratedValue + private Long id; + + private String name; + private String category; + private String location; +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/entity/User.java b/recruitment-service/src/main/java/com/example/recruitment/entity/User.java new file mode 100644 index 0000000..b04e733 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/entity/User.java @@ -0,0 +1,17 @@ +package com.example.recruitment.entity; + +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Getter @Setter +@NoArgsConstructor +@AllArgsConstructor +public class User { + + @Id @GeneratedValue + private Long id; + + private String name; + private String email; +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/exception/CustomException.java b/recruitment-service/src/main/java/com/example/recruitment/exception/CustomException.java new file mode 100644 index 0000000..da26b09 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/exception/CustomException.java @@ -0,0 +1,17 @@ +package com.example.recruitment.exception; + +import lombok.Getter; + +@Getter +public class CustomException extends RuntimeException { + private final ErrorCode errorCode; + + public CustomException(ErrorCode errorCode) { + this.errorCode = errorCode; + } + + @Override + public String getMessage() { + return errorCode.getMessage(); + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/exception/ErrorCode.java b/recruitment-service/src/main/java/com/example/recruitment/exception/ErrorCode.java new file mode 100644 index 0000000..a88f6f7 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/exception/ErrorCode.java @@ -0,0 +1,18 @@ +package com.example.recruitment.exception; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +@AllArgsConstructor +public enum ErrorCode { + BAD_REQUEST(2000, HttpStatus.BAD_REQUEST, "잘못된 요청입니다."), + NOT_FOUND(2007, HttpStatus.NOT_FOUND, "리소스를 찾을 수 없습니다."), + FORBIDDEN(2006, HttpStatus.FORBIDDEN, "권한이 없습니다."), + INTERNAL_ERROR(3000, HttpStatus.INTERNAL_SERVER_ERROR, "서버 내부 오류입니다."); + + private final int code; + private final HttpStatus status; + private final String message; +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/exception/GlobalExceptionHandler.java b/recruitment-service/src/main/java/com/example/recruitment/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..dd5a88a --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/exception/GlobalExceptionHandler.java @@ -0,0 +1,54 @@ +package com.example.recruitment.exception; + +import com.example.recruitment.common.ApiResponse; +import com.example.recruitment.common.FieldErrorDetail; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.List; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(CustomException.class) + public ResponseEntity> handleCustomException(CustomException e) { + ErrorCode ec = e.getErrorCode(); + return ResponseEntity + .status(ec.getStatus()) + .body(ApiResponse.fail(ec.getCode(), ec.getMessage(), ec.getStatus())); + } + + // 유효성 검사 실패 + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationException(MethodArgumentNotValidException e) { + List errorList = e.getBindingResult().getFieldErrors() + .stream() + .map(error -> new FieldErrorDetail(error.getField(), error.getDefaultMessage())) + .toList(); + + return ResponseEntity + .badRequest() + .body(ApiResponse.validationFail(errorList)); + } + + // 그 외 모든 예외 처리 + @ExceptionHandler(Exception.class) + public ResponseEntity> handleGeneralException(Exception e, HttpServletRequest request) throws Exception { + String path = request.getRequestURI(); + + if (path != null && (path.contains("/v3/api-docs") || path.contains("/swagger"))) { + throw e; // Swagger 요청은 예외 처리하지 않고 Spring에게 맡김 +} + + return ResponseEntity + .status(ErrorCode.INTERNAL_ERROR.getStatus()) + .body(ApiResponse.fail( + ErrorCode.INTERNAL_ERROR.getCode(), + ErrorCode.INTERNAL_ERROR.getMessage(), + ErrorCode.INTERNAL_ERROR.getStatus() + )); + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/repository/RecruitmentParticipantRepository.java b/recruitment-service/src/main/java/com/example/recruitment/repository/RecruitmentParticipantRepository.java new file mode 100644 index 0000000..0e371bf --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/repository/RecruitmentParticipantRepository.java @@ -0,0 +1,26 @@ +package com.example.recruitment.repository; + +import com.example.recruitment.entity.Recruitment; +import com.example.recruitment.entity.RecruitmentParticipant; +import com.example.recruitment.entity.User; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface RecruitmentParticipantRepository extends JpaRepository { + + // 특정 유저가 특정 모집글에 이미 참여했는지 확인 + Optional findByUserIdAndRecruitmentId(Long userId, Long recruitmentId); + + // 특정 모집글에 참여한 인원 수 카운트 + long countByRecruitmentId(Long recruitmentId); + + List findByRecruitmentId(Long recruitmentId); + + List findByUserId(Long userId); + + //참여 여부 확인 메서드 + boolean existsByRecruitmentAndUser(Recruitment recruitment, User user); +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/repository/RecruitmentRepository.java b/recruitment-service/src/main/java/com/example/recruitment/repository/RecruitmentRepository.java new file mode 100644 index 0000000..e26be0d --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/repository/RecruitmentRepository.java @@ -0,0 +1,14 @@ +package com.example.recruitment.repository; + +import com.example.recruitment.entity.Recruitment; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RecruitmentRepository extends JpaRepository { + List findByStatus(String status); + List findByUserId(Long userId); + + +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/repository/StoreRepository.java b/recruitment-service/src/main/java/com/example/recruitment/repository/StoreRepository.java new file mode 100644 index 0000000..3fd1e99 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/repository/StoreRepository.java @@ -0,0 +1,7 @@ +package com.example.recruitment.repository; + +import com.example.recruitment.entity.Store; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StoreRepository extends JpaRepository { +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/repository/UserRepository.java b/recruitment-service/src/main/java/com/example/recruitment/repository/UserRepository.java new file mode 100644 index 0000000..f25ccd9 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.example.recruitment.repository; + +import com.example.recruitment.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java b/recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java new file mode 100644 index 0000000..b1259a3 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java @@ -0,0 +1,42 @@ +package com.example.recruitment.service; + +import com.example.recruitment.dto.order.OrderRequestDto; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +@Service +public class OrderClient { + + private final RestTemplate restTemplate = new RestTemplate(); + + @Value("${order.server.url}") + private String serverUrl; + + @Value("${order.server.path}") + private String path; + + public Long createOrder(OrderRequestDto requestDto) { + String fullUrl = serverUrl + path; + + ResponseEntity response = restTemplate.postForEntity(fullUrl, requestDto, Map.class); + + if (response.getStatusCode().is2xxSuccessful()) { + Map responseBody = response.getBody(); + + if (responseBody != null && responseBody.containsKey("data")) { + Map data = (Map) responseBody.get("data"); + + if (data != null && data.containsKey("orderId")) { + return Long.valueOf(data.get("orderId").toString()); + } + } + throw new RuntimeException("응답에 orderId 없음"); + } + + throw new RuntimeException("주문 생성 실패: " + response.getStatusCode()); + } +} diff --git a/recruitment-service/src/main/java/com/example/recruitment/service/RecruitmentService.java b/recruitment-service/src/main/java/com/example/recruitment/service/RecruitmentService.java new file mode 100644 index 0000000..7b96fc9 --- /dev/null +++ b/recruitment-service/src/main/java/com/example/recruitment/service/RecruitmentService.java @@ -0,0 +1,92 @@ +package com.example.recruitment.service; + +import com.example.recruitment.dto.RecruitmentRequestDto; +import com.example.recruitment.dto.order.OrderRequestDto; +import com.example.recruitment.entity.Recruitment; +import com.example.recruitment.entity.RecruitmentParticipant; +import com.example.recruitment.entity.Store; +import com.example.recruitment.entity.User; +import com.example.recruitment.repository.RecruitmentParticipantRepository; +import com.example.recruitment.repository.RecruitmentRepository; +import com.example.recruitment.repository.StoreRepository; +import com.example.recruitment.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class RecruitmentService { + + private final RecruitmentRepository recruitmentRepository; + private final UserRepository userRepository; + private final StoreRepository storeRepository; + private final RecruitmentParticipantRepository participantRepository; + private final OrderClient orderClient; // 주문 서버와 통신할 client + + /** + * 모집글 생성 시: + * - 사용자 및 가게 조회 + * - 모집글 저장 + * - 주문 서버에 주문 생성 요청 + * - 생성된 orderId를 모집글에 저장 + */ + @Transactional + public void createRecruitment(RecruitmentRequestDto dto) { + User user = userRepository.findById(dto.getUserId()) + .orElseThrow(() -> new RuntimeException("사용자 없음")); + Store store = storeRepository.findById(dto.getStoreId()) + .orElseThrow(() -> new RuntimeException("가게 없음")); + + Recruitment recruitment = new Recruitment(); + recruitment.setUser(user); + recruitment.setStore(store); + recruitment.setTitle(dto.getTitle()); + recruitment.setDescription(dto.getDescription()); + recruitment.setDeadlineTime(dto.getDeadlineTime()); + recruitment.setStatus("RECRUITING"); + recruitment.setCategory(dto.getCategory()); + recruitmentRepository.save(recruitment); + + // 주문 서버에 주문 생성 요청 + OrderRequestDto orderDto = dto.toOrderRequestDto(); + orderDto.setGroupId(recruitment.getId()); + Long orderId = orderClient.createOrder(orderDto); + + // orderId를 모집글에 저장 + recruitment.setOrderId(orderId); + recruitmentRepository.save(recruitment); + } + + /** + * 모집글 참여 시: + * - 사용자 및 모집글 조회 + * - 중복 참여 여부 확인 + * - 주문 서버에 주문 생성 요청 + * - 생성된 orderId를 RecruitmentParticipant에 저장 + */ + @Transactional + public void joinRecruitment(Long recruitmentId, Long userId, OrderRequestDto orderDto) { + Recruitment recruitment = recruitmentRepository.findById(recruitmentId) + .orElseThrow(() -> new RuntimeException("모집 없음")); + User user = userRepository.findById(userId) + .orElseThrow(() -> new RuntimeException("사용자 없음")); + + boolean alreadyJoined = participantRepository.existsByRecruitmentAndUser(recruitment, user); + if (alreadyJoined) { + throw new RuntimeException("이미 참여한 모집입니다."); + } + + // 주문 서버에 주문 생성 요청 + orderDto.setGroupId(recruitmentId); + orderDto.setUserId(userId); + Long orderId = orderClient.createOrder(orderDto); + + // 참여자 등록 + 주문 ID 저장 + RecruitmentParticipant participant = new RecruitmentParticipant(); + participant.setRecruitment(recruitment); + participant.setUser(user); + participant.setOrderId(orderId); + participantRepository.save(participant); + } +} diff --git a/recruitment-service/src/main/resources/application.properties b/recruitment-service/src/main/resources/application.properties new file mode 100644 index 0000000..3a429be --- /dev/null +++ b/recruitment-service/src/main/resources/application.properties @@ -0,0 +1,12 @@ +spring.application.name=recruitment +spring.datasource.url=jdbc:mysql://localhost:3306/recruitment_db?serverTimezone=Asia/Seoul +spring.datasource.username=root +spring.datasource.password=040320 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true + +order.server.url=http://54.66.149.225:8100 +order.server.path=/api/v1/orders diff --git a/recruitment-service/src/test/java/com/example/recruitment/RecruitmentApplicationTests.java b/recruitment-service/src/test/java/com/example/recruitment/RecruitmentApplicationTests.java new file mode 100644 index 0000000..de54f7d --- /dev/null +++ b/recruitment-service/src/test/java/com/example/recruitment/RecruitmentApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.recruitment; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RecruitmentApplicationTests { + + @Test + void contextLoads() { + } + +}