diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..62692ebd00 --- /dev/null +++ b/.gitignore @@ -0,0 +1,193 @@ +# Created by https://www.toptal.com/developers/gitignore/api/macos,gradle,java,git,intellij+all +# Edit at https://www.toptal.com/developers/gitignore?templates=macos,gradle,java,git,intellij+all + +### Git ### +# Created by git for backups. To disable backups in Git: +# $ git config --global mergetool.keepBackup false +*.orig + +# Created by git when using merge tools for conflicts +*.BACKUP.* +*.BASE.* +*.LOCAL.* +*.REMOTE.* +*_BACKUP_*.txt +*_BASE_*.txt +*_LOCAL_*.txt +*_REMOTE_*.txt + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/macos,gradle,java,git,intellij+all \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 0000000000..3d6d37a6eb --- /dev/null +++ b/HELP.md @@ -0,0 +1,20 @@ +# Read Me First +The following was discovered as part of building this project: + +* The JVM level was changed from '16' to '17', review the [JDK Version Range](https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Versions#jdk-version-range) on the wiki for more details. +* The original package name 'team.marco.voucher-management-system' is invalid and this project uses 'team.marco.voucher_management_system' instead. + +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Gradle documentation](https://docs.gradle.org) +* [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.1.4/gradle-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.1.4/gradle-plugin/reference/html/#build-image) + +### Additional Links +These additional references should also help you: + +* [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..2d55d6bfd6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,37 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'team.marco' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + // Spring boot + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation('nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect') + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + + // Test + testImplementation 'org.springframework.boot:spring-boot-starter-test' + + // Jackson + implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' + + // Mysql + implementation group: 'com.mysql', name: 'mysql-connector-j', version: '8.1.0' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..7f93135c49 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 0000000000..ac72c34e8a --- /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.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000..0adc8e1a53 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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. +# + +############################################################################## +# +# 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/subprojects/plugins/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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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=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=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 $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000000..6689b85bee --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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 + +@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. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +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/httpRequest/voucher-request.http b/httpRequest/voucher-request.http new file mode 100644 index 0000000000..cef34bf215 --- /dev/null +++ b/httpRequest/voucher-request.http @@ -0,0 +1,25 @@ +### 쿠폰 전체 목록 조회 +GET http://localhost:8080/api/vouchers +Accept: application/json + +### 쿠폰 타입으로 조회 +GET http://localhost:8080/api/vouchers?voucherType=FIXED +Accept: application/json + +### 쿠폰 ID로 조회 +GET http://localhost:8080/api/vouchers/2 +Accept: application/json + +### 쿠폰 생성 +POST http://localhost:8080/api/vouchers +Accept: application/json +Content-Type: application/json + +{ + "voucherType": "FIXED", + "discountValue": 5000 +} + +### 쿠폰 삭제 By 쿠폰 ID +DELETE http://localhost:8080/api/vouchers/1 +Accept: application/json \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000000..d6396d13ef --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'voucher-management-system' diff --git a/src/main/java/team/marco/voucher_management_system/VoucherManagementSystemApplication.java b/src/main/java/team/marco/voucher_management_system/VoucherManagementSystemApplication.java new file mode 100644 index 0000000000..a4e79c6ca0 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/VoucherManagementSystemApplication.java @@ -0,0 +1,17 @@ +package team.marco.voucher_management_system; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import team.marco.voucher_management_system.view.consoleapp.ConsoleVoucherApplication; + +@SpringBootApplication +public class VoucherManagementSystemApplication { + + public static void main(String[] args) { + ApplicationContext context = SpringApplication.run(VoucherManagementSystemApplication.class, args); + + ConsoleVoucherApplication application = context.getBean(ConsoleVoucherApplication.class); + application.run(); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/configuration/JdbcTemplateConfig.java b/src/main/java/team/marco/voucher_management_system/configuration/JdbcTemplateConfig.java new file mode 100644 index 0000000000..4a876a0f8a --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/configuration/JdbcTemplateConfig.java @@ -0,0 +1,43 @@ +package team.marco.voucher_management_system.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +import javax.sql.DataSource; + +@Configuration +public class JdbcTemplateConfig { + private final String username; + private final String password; + private final String driverClassName; + private final String url; + + public JdbcTemplateConfig(@Value("${spring.datasource.username}") String username, + @Value("${spring.datasource.password}") String password, + @Value("${spring.datasource.driver-class-name}") String driverClassName, + @Value("${spring.datasource.url}") String url) { + this.username = username; + this.password = password; + this.driverClassName = driverClassName; + this.url = url; + } + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUsername(username); + dataSource.setPassword(password); + dataSource.setDriverClassName(driverClassName); + dataSource.setUrl(url); + + return dataSource; + } + + @Bean + public JdbcTemplate jdbcTemplate(){ + return new JdbcTemplate(dataSource()); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/ApiResponse.java b/src/main/java/team/marco/voucher_management_system/controller/ApiResponse.java new file mode 100644 index 0000000000..cf906f6b3a --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/ApiResponse.java @@ -0,0 +1,49 @@ +package team.marco.voucher_management_system.controller; + +import org.springframework.http.HttpStatus; + +public class ApiResponse { + private int code; + private HttpStatus status; + private String message; + private T data; + + public ApiResponse(HttpStatus status, String message, T data) { + this.code = status.value(); + this.status = status; + this.message = message; + this.data = data; + } + + public static ApiResponse of(HttpStatus httpStatus, String message, T data) { + return new ApiResponse<>(httpStatus, message, data); + } + + public static ApiResponse of(HttpStatus httpStatus, T data) { + return of(httpStatus, httpStatus.name(), data); + } + + public static ApiResponse ok(T data) { + return of(HttpStatus.OK, data); + } + + public static ApiResponse ok() { + return of(HttpStatus.OK, null); + } + + public int getCode() { + return code; + } + + public HttpStatus getStatus() { + return status; + } + + public String getMessage() { + return message; + } + + public T getData() { + return data; + } +} \ No newline at end of file diff --git a/src/main/java/team/marco/voucher_management_system/controller/customer/CustomerController.java b/src/main/java/team/marco/voucher_management_system/controller/customer/CustomerController.java new file mode 100644 index 0000000000..429af298a7 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/customer/CustomerController.java @@ -0,0 +1,47 @@ +package team.marco.voucher_management_system.controller.customer; + +import org.springframework.stereotype.Controller; +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; +import team.marco.voucher_management_system.controller.customer.dto.CustomerResponse; +import team.marco.voucher_management_system.domain.customer.Customer; +import team.marco.voucher_management_system.service.customer.BlacklistService; +import team.marco.voucher_management_system.service.customer.CustomerService; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.UUID; + +@Controller +public class CustomerController { + private final CustomerService customerService; + private final BlacklistService blacklistService; + + public CustomerController(CustomerService customerService, BlacklistService blacklistService) { + this.customerService = customerService; + this.blacklistService = blacklistService; + } + + public List findBlacklist() { + return blacklistService.getBlacklist(); + } + + public boolean isExistCustomer(String customerId) { + try { + customerService.findCustomerById(UUID.fromString(customerId)); + return true; + } catch (NoSuchElementException e) { + return false; + } + } + + public List findAll() { + return customerService.findAllCustomer().stream() + .map(CustomerResponse::of) + .toList(); + } + + public Customer findCustomerByEmail(String email) { + Customer customer = customerService.findCustomerByEmail(email); + return customer; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/customer/dto/CustomerIdAndName.java b/src/main/java/team/marco/voucher_management_system/controller/customer/dto/CustomerIdAndName.java new file mode 100644 index 0000000000..7c5388a8fa --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/customer/dto/CustomerIdAndName.java @@ -0,0 +1,21 @@ +package team.marco.voucher_management_system.controller.customer.dto; + +import java.util.UUID; + +public class CustomerIdAndName { + private final UUID id; + private final String name; + + public CustomerIdAndName(UUID id, String name) { + this.id = id; + this.name = name; + } + + public UUID getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/customer/dto/CustomerResponse.java b/src/main/java/team/marco/voucher_management_system/controller/customer/dto/CustomerResponse.java new file mode 100644 index 0000000000..4682bfb176 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/customer/dto/CustomerResponse.java @@ -0,0 +1,33 @@ +package team.marco.voucher_management_system.controller.customer.dto; + +import team.marco.voucher_management_system.domain.customer.Customer; + +import java.time.LocalDateTime; + +public class CustomerResponse { + private String name; + private String email; + private LocalDateTime createdAt; + + public CustomerResponse(String name, String email, LocalDateTime createdAt) { + this.name = name; + this.email = email; + this.createdAt = createdAt; + } + + public static CustomerResponse of(Customer customer) { + return new CustomerResponse(customer.getName(), customer.getEmail(), customer.getCreatedAt()); + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherApiController.java b/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherApiController.java new file mode 100644 index 0000000000..bab6b79d53 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherApiController.java @@ -0,0 +1,61 @@ +package team.marco.voucher_management_system.controller.voucher; + +import jakarta.annotation.Nullable; +import org.springframework.web.bind.annotation.*; +import team.marco.voucher_management_system.controller.ApiResponse; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherCreateRequest; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherResponse; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; +import team.marco.voucher_management_system.service.voucher.VoucherService; + +import java.util.List; + +@RestController +@RequestMapping("/api/vouchers") +public class VoucherApiController { + private final VoucherService voucherService; + + public VoucherApiController(VoucherService voucherService) { + this.voucherService = voucherService; + } + + @GetMapping + public ApiResponse> findAllVouchers(@Nullable @RequestParam VoucherType voucherType) { + if(voucherType != null) { + List vouchers = voucherService.getVouchersByVoucherType(voucherType).stream() + .map(VoucherResponse::of) + .toList(); + + return ApiResponse.ok(vouchers); + } + + List vouchers = voucherService.getVouchers().stream() + .map(VoucherResponse::of) + .toList(); + + return ApiResponse.ok(vouchers); + } + + @GetMapping("/{voucherId}") + public ApiResponse getVoucher(@PathVariable Long voucherId) { + VoucherResponse voucher = VoucherResponse.of(voucherService.getVoucher(voucherId)); + + return ApiResponse.ok(voucher); + } + + @PostMapping + public ApiResponse createVoucher(@RequestBody VoucherCreateRequest request) { + Voucher voucher = voucherService.createVoucher(request.toServiceRequest()); + VoucherResponse response = VoucherResponse.of(voucher); + + return ApiResponse.ok(response); + } + + @DeleteMapping("/{voucherId}") + public ApiResponse deleteVoucher(@PathVariable Long voucherId) { + voucherService.deleteVoucher(voucherId); + + return ApiResponse.ok(); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherController.java b/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherController.java new file mode 100644 index 0000000000..75b6066843 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherController.java @@ -0,0 +1,35 @@ +package team.marco.voucher_management_system.controller.voucher; + +import org.springframework.stereotype.Controller; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherCreateRequest; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherResponse; +import team.marco.voucher_management_system.service.voucher.VoucherService; + +import java.util.List; + +@Controller +public class VoucherController { + private final VoucherService voucherService; + + public VoucherController(VoucherService voucherService) { + this.voucherService = voucherService; + } + + public void createVoucher(VoucherCreateRequest request) { + voucherService.createVoucher(request.toServiceRequest()); + } + + public VoucherResponse getVoucher(String voucherId) { + return VoucherResponse.of(voucherService.getVoucher(Long.valueOf(voucherId))); + } + + public List getVouchers() { + return voucherService.getVouchers().stream() + .map(VoucherResponse::of) + .toList(); + } + + public void deleteVoucher(String voucherId) { + voucherService.deleteVoucher(Long.valueOf(voucherId)); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherViewController.java b/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherViewController.java new file mode 100644 index 0000000000..442f8bb37d --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/voucher/VoucherViewController.java @@ -0,0 +1,87 @@ +package team.marco.voucher_management_system.controller.voucher; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherResponse; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; +import team.marco.voucher_management_system.service.voucher.VoucherCreateServiceRequest; +import team.marco.voucher_management_system.service.voucher.VoucherService; + +import java.util.List; + +@Controller +@RequestMapping("/vouchers") +public class VoucherViewController { + private final VoucherService voucherService; + + public VoucherViewController(VoucherService voucherService) { + this.voucherService = voucherService; + } + + @GetMapping + public String findAllVouchers(Model model) { + getVouchersAndAddToModel(model); + + return "voucher/voucher_list"; + } + + @GetMapping("/{voucherId}") + public String findVoucher(@PathVariable Long voucherId, Model model) { + Voucher voucher = voucherService.getVoucher(voucherId); + + model.addAttribute("voucher", voucher); + + return "voucher/voucher_detail"; + } + + @GetMapping("/create") + public String findVoucherCreateForm() { + return "voucher/voucher_create_form"; + } + + @PostMapping + public String createVoucher(@RequestParam("voucherType") String voucherType, + @RequestParam("discountValue") int discountValue, + Model model) { + validateDiscountValue(discountValue); + + voucherService.createVoucher(new VoucherCreateServiceRequest( + VoucherType.valueOf(voucherType), + discountValue) + ); + + getVouchersAndAddToModel(model); + + return "voucher/voucher_list"; + } + + @DeleteMapping("/{voucherId}") + public String deleteVoucher(@PathVariable Long voucherId, Model model) { + voucherService.deleteVoucher(voucherId); + + getVouchersAndAddToModel(model); + + return "voucher/voucher_list"; + } + + private void getVouchersAndAddToModel(Model model) { + List vouchers = vouchersToVoucherResponses(voucherService.getVouchers()); + model.addAttribute("vouchers", vouchers); + } + + private List vouchersToVoucherResponses(List vouchers) { + return vouchers.stream() + .map(VoucherResponse::of) + .toList(); + } + + private static boolean isNotPositive(int discountValue) { + return discountValue <= 0; + } + + private static void validateDiscountValue(int discountValue) { + if (isNotPositive(discountValue)) throw new IllegalArgumentException("할인 금액 또는 할인율은 양수입니다."); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/voucher/dto/VoucherCreateRequest.java b/src/main/java/team/marco/voucher_management_system/controller/voucher/dto/VoucherCreateRequest.java new file mode 100644 index 0000000000..6c7040e091 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/voucher/dto/VoucherCreateRequest.java @@ -0,0 +1,38 @@ +package team.marco.voucher_management_system.controller.voucher.dto; + +import team.marco.voucher_management_system.domain.voucher.VoucherType; +import team.marco.voucher_management_system.service.voucher.VoucherCreateServiceRequest; + +public class VoucherCreateRequest { + private VoucherType voucherType; + private int discountValue; + + public VoucherCreateRequest(VoucherType voucherType, int discountValue) { + validateDiscountValue(discountValue); + + this.voucherType = voucherType; + this.discountValue = discountValue; + } + + public VoucherCreateServiceRequest toServiceRequest() { + return new VoucherCreateServiceRequest( + voucherType, + discountValue); + } + + public VoucherType getVoucherType() { + return voucherType; + } + + public int getDiscountValue() { + return discountValue; + } + + private static void validateDiscountValue(int discountValue) { + if (isNotPositive(discountValue)) throw new IllegalArgumentException("할인 금액 또는 할인율은 양수입니다."); + } + + private static boolean isNotPositive(int discountValue) { + return discountValue <= 0; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/controller/voucher/dto/VoucherResponse.java b/src/main/java/team/marco/voucher_management_system/controller/voucher/dto/VoucherResponse.java new file mode 100644 index 0000000000..cfd00d5628 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/controller/voucher/dto/VoucherResponse.java @@ -0,0 +1,33 @@ +package team.marco.voucher_management_system.controller.voucher.dto; + +import team.marco.voucher_management_system.domain.voucher.Voucher; + +import java.util.UUID; + +public class VoucherResponse { + private Long id; + private UUID code; + private String name; + + public VoucherResponse(Long id, UUID code, String name) { + this.id = id; + this.code = code; + this.name = name; + } + + public static VoucherResponse of(Voucher voucher) { + return new VoucherResponse(voucher.getId(), voucher.getCode(), voucher.getName()); + } + + public Long getId() { + return id; + } + + public UUID getCode() { + return code; + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/domain/customer/Customer.java b/src/main/java/team/marco/voucher_management_system/domain/customer/Customer.java new file mode 100644 index 0000000000..28683a4c4e --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/domain/customer/Customer.java @@ -0,0 +1,66 @@ +package team.marco.voucher_management_system.domain.customer; + +import java.time.LocalDateTime; +import java.util.UUID; + +public class Customer { + private final UUID id; + private final String name; + private final String email; + private final LocalDateTime createdAt; + + private Customer(UUID id, String name, String email, LocalDateTime createdAt) { + this.id = id; + this.name = name; + this.email = email; + this.createdAt = createdAt; + } + + public UUID getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public static class Builder { + private UUID id = UUID.randomUUID(); + private String name; + private String email; + private LocalDateTime createdAt = LocalDateTime.now(); + + public Builder(String name, String email) { + validateStringNotBlank(name); + validateStringNotBlank(email); + this.name = name; + this.email = email; + } + + public Builder id(UUID id) { + this.id = id; + return this; + } + + public Builder createdAt(LocalDateTime createdAt) { + this.createdAt = createdAt; + return this; + } + + public Customer build() { + return new Customer(id, name, email, createdAt); + } + } + + private static void validateStringNotBlank(String name) { + if(name == null || name.isBlank()) throw new IllegalArgumentException("빈 문자열 일 수 없습니다."); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/domain/voucher/Voucher.java b/src/main/java/team/marco/voucher_management_system/domain/voucher/Voucher.java new file mode 100644 index 0000000000..1e115e1047 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/domain/voucher/Voucher.java @@ -0,0 +1,102 @@ +package team.marco.voucher_management_system.domain.voucher; + +import java.util.UUID; + +import static java.text.MessageFormat.format; + +public class Voucher { + private static final int MIN_AMOUNT = 1_000; + private static final int MAX_AMOUNT = 100_000; + private static final int MIN_PERCENT = 5; + private static final int MAX_PERCENT = 100; + + private final Long id; + private final UUID code; + private final VoucherType voucherType; + private final int discountValue; + private String name; + + private Voucher(Long id, UUID code, VoucherType voucherType, int discountValue, String name) { + this.id = id; + this.code = code; + this.voucherType = voucherType; + this.discountValue = discountValue; + this.name = name; + } + + public Long getId() { + return id; + } + + public UUID getCode() { + return code; + } + + public VoucherType getVoucherType() { + return voucherType; + } + + public int getDiscountValue() { + return discountValue; + } + + public String getName() { + return name; + } + + public static class Builder { + private Long id; + private VoucherType voucherType; + private int discountValue; + private UUID code = UUID.randomUUID(); + private String name; + + public Builder(Long id, VoucherType voucherType, int discountValue) { + this.id = id; + this.voucherType = voucherType; + this.discountValue = discountValue; + switch (voucherType) { + case FIXED -> name = format("{0}원 할인 쿠폰", discountValue); + case PERCENT -> name = format("{0}% 할인 쿠폰", discountValue); + } + } + + public Builder code(UUID code) { + this.code = code; + return this; + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Voucher build() { + switch (voucherType) { + case FIXED -> validateAmount(discountValue); + case PERCENT -> validatePercent(discountValue); + } + return new Voucher(id, code, voucherType, discountValue, name); + } + + private void validateAmount(int amount) { + if(amount < MIN_AMOUNT || amount > MAX_AMOUNT) { + throw new IllegalArgumentException(getAmountPolicy()); + } + } + + private void validatePercent(int percent) { + if(percent < MIN_PERCENT || percent > MAX_PERCENT) { + throw new IllegalArgumentException(getPercentPolicy()); + } + } + } + + private static String getAmountPolicy() { + return format("할인 금액은 {0}원 이상, {1}원 이하이어야 합니다.", MIN_AMOUNT, MAX_AMOUNT); + } + + private static String getPercentPolicy() { + return format("할인 비율은 {0}% 이상, {1}% 이하이어야 합니다.", MIN_PERCENT, MAX_PERCENT); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/domain/voucher/VoucherType.java b/src/main/java/team/marco/voucher_management_system/domain/voucher/VoucherType.java new file mode 100644 index 0000000000..612202b782 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/domain/voucher/VoucherType.java @@ -0,0 +1,5 @@ +package team.marco.voucher_management_system.domain.voucher; + +public enum VoucherType { + FIXED, PERCENT +} diff --git a/src/main/java/team/marco/voucher_management_system/error/ErrorMessage.java b/src/main/java/team/marco/voucher_management_system/error/ErrorMessage.java new file mode 100644 index 0000000000..2e8078a9b8 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/error/ErrorMessage.java @@ -0,0 +1,12 @@ +package team.marco.voucher_management_system.error; + +public class ErrorMessage { + public static final String CUSTOMER_ID_INVALID = "올바른 사용자 아이디가 아닙니다."; + public static final String INVALID_EMAIL = "해당 이메일의 사용자는 존재하지 않습니다."; + public static final String WRONG_INPUT = "올바르지 않은 입력입니다."; + public static final String NUMBER_REQUIRED = "숫자를 입력해 주세요."; + public static final String CANNOT_CREATE_VOUCHER = "쿠폰을 추가하는 과정에서 오류가 발생했습니다."; + public static final String CANNOT_CREATE_CUSTOMER = "사용자를 추가하는 과정에서 오류가 발생했습니다."; + public static final String FILE_ERROR = "파일을 처리하는 과정에서 에러가 발생했습니다."; + public static final String PROGRAM_ERROR = "프로그램에 에러가 발생했습니다."; +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/custromer/BlacklistRepository.java b/src/main/java/team/marco/voucher_management_system/repository/custromer/BlacklistRepository.java new file mode 100644 index 0000000000..a3632555f1 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/custromer/BlacklistRepository.java @@ -0,0 +1,9 @@ +package team.marco.voucher_management_system.repository.custromer; + +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; + +import java.util.List; + +public interface BlacklistRepository { + List findAll(); +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/custromer/CsvBlacklistRepository.java b/src/main/java/team/marco/voucher_management_system/repository/custromer/CsvBlacklistRepository.java new file mode 100644 index 0000000000..ca41758c8c --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/custromer/CsvBlacklistRepository.java @@ -0,0 +1,47 @@ +package team.marco.voucher_management_system.repository.custromer; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Repository; +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; + +import static team.marco.voucher_management_system.util.UUIDUtil.stringToUUID; + +@Repository +public class CsvBlacklistRepository implements BlacklistRepository { + private static final String DELIMITER_REGULAR_EXPRESSION = "[;,]"; + private final List blacklist; + + public CsvBlacklistRepository(@Value("${file.path.blacklist}") String path) { + blacklist = loadBlacklist(path); + } + + private List loadBlacklist(String path) { + try (BufferedReader reader = Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8)) { + reader.readLine(); // skip header + return storedDataToCustomerIdAndName(reader); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @Override + public List findAll() { + return Collections.unmodifiableList(blacklist); + } + + private static List storedDataToCustomerIdAndName(BufferedReader reader) { + return reader.lines() + .map(s -> s.split(DELIMITER_REGULAR_EXPRESSION)) + .map(data -> new CustomerIdAndName(stringToUUID(data[0]), data[1])) + .toList(); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/custromer/CustomerRepository.java b/src/main/java/team/marco/voucher_management_system/repository/custromer/CustomerRepository.java new file mode 100644 index 0000000000..b3c833e255 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/custromer/CustomerRepository.java @@ -0,0 +1,14 @@ +package team.marco.voucher_management_system.repository.custromer; + +import team.marco.voucher_management_system.domain.customer.Customer; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface CustomerRepository { + Customer insert(Customer customer); + List findAll(); + Optional findById(UUID customerId); + Optional findByEmail(String email); +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/custromer/JdbcCustomerRepository.java b/src/main/java/team/marco/voucher_management_system/repository/custromer/JdbcCustomerRepository.java new file mode 100644 index 0000000000..d3486213e8 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/custromer/JdbcCustomerRepository.java @@ -0,0 +1,92 @@ +package team.marco.voucher_management_system.repository.custromer; + +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import team.marco.voucher_management_system.domain.customer.Customer; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.*; + +import static team.marco.voucher_management_system.error.ErrorMessage.CANNOT_CREATE_CUSTOMER; +import static team.marco.voucher_management_system.util.UUIDUtil.bytesToUUID; +import static team.marco.voucher_management_system.util.UUIDUtil.uuidToBytes; + +@Repository +public class JdbcCustomerRepository implements CustomerRepository { + + private static final String SELECT_ALL_SQL = "SELECT * FROM customers"; + private static final String SELECT_BY_ID_SQL = "SELECT * FROM customers WHERE customer_id = ?"; + private static final String SELECT_BY_EMAIL_SQL = "SELECT * FROM customers WHERE email = ?"; + private static final String INSERT_SQL = "INSERT INTO customers(customer_id, name, email, created_at) VALUES (?, ?, ?, ?)"; + + private final JdbcTemplate jdbcTemplate; + + public JdbcCustomerRepository(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + @Override + public Customer insert(Customer customer) { + int update = jdbcTemplate.update(INSERT_SQL, + uuidToBytes(customer.getId()), + customer.getName(), + customer.getEmail(), + Timestamp.valueOf(customer.getCreatedAt())); + + if(update != 1) { + throw new RuntimeException(CANNOT_CREATE_CUSTOMER); + } + + return customer; + } + + @Override + public List findAll() { + List customers = new ArrayList<>(); + jdbcTemplate.query(SELECT_ALL_SQL, (resultSet, rowNum) -> customers.add(resultSetToCustomer(resultSet))); + + return Collections.unmodifiableList(customers); + } + + @Override + public Optional findById(UUID customerId) { + try { + Customer customer = jdbcTemplate.queryForObject(SELECT_BY_ID_SQL, + (resultSet, rowNum) -> resultSetToCustomer(resultSet), + uuidToBytes(customerId)); + + return Optional.of(customer); + } catch (DataAccessException e) { + return Optional.empty(); + } + } + + @Override + public Optional findByEmail(String email) { + try { + Customer customer = jdbcTemplate.queryForObject(SELECT_BY_EMAIL_SQL, + (resultSet, rowNum) -> resultSetToCustomer(resultSet), + email); + + return Optional.of(customer); + } catch (DataAccessException e) { + return Optional.empty(); + } + } + + private Customer resultSetToCustomer(ResultSet resultSet) throws SQLException { + UUID id = bytesToUUID(resultSet.getBytes("customer_id")); + String name = resultSet.getString("name"); + String email = resultSet.getString("email"); + LocalDateTime createdAt = resultSet.getTimestamp("created_at").toLocalDateTime(); + + return new Customer.Builder(name, email) + .id(id) + .createdAt(createdAt) + .build(); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/voucher/JdbcVoucherRepository.java b/src/main/java/team/marco/voucher_management_system/repository/voucher/JdbcVoucherRepository.java new file mode 100644 index 0000000000..093d1dc70c --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/voucher/JdbcVoucherRepository.java @@ -0,0 +1,110 @@ +package team.marco.voucher_management_system.repository.voucher; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +import static team.marco.voucher_management_system.error.ErrorMessage.CANNOT_CREATE_VOUCHER; +import static team.marco.voucher_management_system.util.UUIDUtil.bytesToUUID; +import static team.marco.voucher_management_system.util.UUIDUtil.uuidToBytes; + +@Primary +@Repository +public class JdbcVoucherRepository implements VoucherRepository { + private static final Logger logger = LoggerFactory.getLogger(JdbcVoucherRepository.class); + + private static final String INSERT_SQL = "INSERT INTO vouchers(voucher_id, voucher_type, discount_value, code, name) VALUES (?, ?, ?, ?, ?)"; + private static final String SELECT_ALL_SQL = "SELECT * FROM vouchers"; + private static final String SELECT_ALL_BY_TYPE_SQL = "SELECT * FROM vouchers WHERE voucher_type = ?"; + private static final String SELECT_BY_ID_SQL = "SELECT * FROM vouchers WHERE voucher_id = ?"; + private static final String DELETE_BY_ID_SQL = "DELETE From vouchers WHERE voucher_id = ?"; + private static final String SELECT_MAXIMUM_ID = "SELECT v.voucher_id From vouchers v ORDER BY voucher_id DESC LIMIT 1"; + private static final String SELECT_TOTAL_COUNTS = "SELECT count(*) From vouchers v"; + + private final JdbcTemplate jdbcTemplate; + + public JdbcVoucherRepository(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + @Override + public Voucher save(Voucher voucher) { + int update = jdbcTemplate.update(INSERT_SQL, + voucher.getId(), + voucher.getVoucherType().name(), + voucher.getDiscountValue(), + uuidToBytes(voucher.getCode()), + voucher.getName()); + + if(update != 1) { + logger.error(CANNOT_CREATE_VOUCHER); + throw new RuntimeException(CANNOT_CREATE_VOUCHER); + } + + return voucher; + } + + @Override + public List findAll() { + List vouchers = new ArrayList<>(); + jdbcTemplate.query(SELECT_ALL_SQL + , (resultSet, rowNum) -> vouchers.add(resultSetToVoucher(resultSet))); + + return Collections.unmodifiableList(vouchers); + } + + @Override + public List findAllByVoucherType(VoucherType type) { + List vouchers = new ArrayList<>(); + jdbcTemplate.query(SELECT_ALL_BY_TYPE_SQL + , (resultSet, rowNum) -> vouchers.add(resultSetToVoucher(resultSet)) + , type.name()); + + return Collections.unmodifiableList(vouchers); + } + + @Override + public Optional findById(Long voucherId) { + return Optional.of(jdbcTemplate.queryForObject(SELECT_BY_ID_SQL + , (resultSet, rowNum) -> resultSetToVoucher(resultSet) + , voucherId)); + } + + @Override + public void deleteById(Long voucherId) { + jdbcTemplate.update(DELETE_BY_ID_SQL, voucherId); + } + + @Override + public Optional findLatestVoucherId() { + Long size = jdbcTemplate.queryForObject(SELECT_TOTAL_COUNTS, Long.class); + if(isZero(size)) return Optional.empty(); + + return Optional.of(jdbcTemplate.queryForObject(SELECT_MAXIMUM_ID, Long.class)); + } + + private Voucher resultSetToVoucher(ResultSet resultSet) throws SQLException { + Long voucherId = resultSet.getLong("voucher_id"); + VoucherType voucherType = VoucherType.valueOf(resultSet.getString("voucher_type")); + int discountValue = resultSet.getInt("discount_value"); + UUID code = bytesToUUID(resultSet.getBytes("code")); + String name = resultSet.getString("name"); + + return new Voucher.Builder(voucherId, voucherType, discountValue) + .code(code) + .name(name) + .build(); + } + + private static boolean isZero(Long num) { + return num == 0; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/voucher/JsonFileVoucherRepository.java b/src/main/java/team/marco/voucher_management_system/repository/voucher/JsonFileVoucherRepository.java new file mode 100644 index 0000000000..f29b536af6 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/voucher/JsonFileVoucherRepository.java @@ -0,0 +1,104 @@ +package team.marco.voucher_management_system.repository.voucher; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Repository; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +@Repository +public class JsonFileVoucherRepository implements VoucherRepository, DisposableBean { + private final Map voucherMap; + private final ObjectMapper objectMapper; + private final File file; + + public JsonFileVoucherRepository(@Value("${file.path.voucher_data}") String path) { + objectMapper = new ObjectMapper(); + file = new File(path); + + voucherMap = loadVoucherMap(); + } + + private Map loadVoucherMap() { + Map loadedVouchers = new ConcurrentHashMap<>(); + if (!file.exists()) { + return loadedVouchers; + } + + ObjectReader objectReader = objectMapper.readerForListOf(Voucher.class); + List vouchers; + + try { + vouchers = objectReader.readValue(file); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + vouchers.forEach(voucher -> loadedVouchers.put(voucher.getId(), voucher)); + + return loadedVouchers; + } + + @Override + public Voucher save(Voucher voucher) { + voucherMap.put(voucher.getId(), voucher); + + return voucher; + } + + @Override + public List findAll() { + return voucherMap.values().stream() + .toList(); + } + + @Override + public List findAllByVoucherType(VoucherType type) { + return voucherMap.values().stream() + .filter(v -> isSameType(type, v)) + .toList(); + } + + @Override + public Optional findById(Long voucherId) { + if(voucherMap.containsKey(voucherId)) { + return Optional.of(voucherMap.get(voucherId)); + } else return Optional.empty(); + } + + @Override + public void deleteById(Long voucherId) { + voucherMap.remove(voucherId); + } + + @Override + public Optional findLatestVoucherId() { + return voucherMap.keySet().stream() + .max(Comparator.naturalOrder()); + } + + @Override + public void destroy() { + try { + List vouchers = voucherMap.values().stream().toList(); + objectMapper.writeValue(file, vouchers); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static boolean isSameType(VoucherType type, Voucher v) { + return v.getVoucherType() == type; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/voucher/MemoryVoucherRepository.java b/src/main/java/team/marco/voucher_management_system/repository/voucher/MemoryVoucherRepository.java new file mode 100644 index 0000000000..00153896f4 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/voucher/MemoryVoucherRepository.java @@ -0,0 +1,58 @@ +package team.marco.voucher_management_system.repository.voucher; + +import org.springframework.stereotype.Repository; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +@Repository +public class MemoryVoucherRepository implements VoucherRepository { + private final Map voucherMap = new ConcurrentHashMap<>(); + + @Override + public Voucher save(Voucher voucher) { + voucherMap.put(voucher.getId(), voucher); + + return voucher; + } + + @Override + public List findAll() { + return voucherMap.values().stream() + .toList(); + } + + @Override + public List findAllByVoucherType(VoucherType type) { + return voucherMap.values().stream() + .filter(v -> isSameType(type, v)) + .toList(); + } + + @Override + public Optional findById(Long voucherId) { + if(voucherMap.containsKey(voucherId)) { + return Optional.of(voucherMap.get(voucherId)); + } else return Optional.empty(); + } + + @Override + public void deleteById(Long voucherId) { + voucherMap.remove(voucherId); + } + + @Override + public Optional findLatestVoucherId() { + return voucherMap.keySet().stream() + .max(Comparator.naturalOrder()); + } + + private static boolean isSameType(VoucherType type, Voucher v) { + return v.getVoucherType() == type; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/repository/voucher/VoucherRepository.java b/src/main/java/team/marco/voucher_management_system/repository/voucher/VoucherRepository.java new file mode 100644 index 0000000000..9a6c62913f --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/repository/voucher/VoucherRepository.java @@ -0,0 +1,21 @@ +package team.marco.voucher_management_system.repository.voucher; + +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; + +import java.util.List; +import java.util.Optional; + +public interface VoucherRepository { + Voucher save(Voucher voucher); + + List findAll(); + + List findAllByVoucherType(VoucherType type); + + Optional findById(Long voucherId); + + void deleteById(Long voucherId); + + Optional findLatestVoucherId(); +} diff --git a/src/main/java/team/marco/voucher_management_system/service/customer/BlacklistService.java b/src/main/java/team/marco/voucher_management_system/service/customer/BlacklistService.java new file mode 100644 index 0000000000..ed615faed7 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/service/customer/BlacklistService.java @@ -0,0 +1,20 @@ +package team.marco.voucher_management_system.service.customer; + +import org.springframework.stereotype.Service; +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; +import team.marco.voucher_management_system.repository.custromer.BlacklistRepository; + +import java.util.List; + +@Service +public class BlacklistService { + private final BlacklistRepository blacklistRepository; + + public BlacklistService(BlacklistRepository blacklistRepository) { + this.blacklistRepository = blacklistRepository; + } + + public List getBlacklist() { + return blacklistRepository.findAll(); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/service/customer/CustomerService.java b/src/main/java/team/marco/voucher_management_system/service/customer/CustomerService.java new file mode 100644 index 0000000000..a6bcc412d9 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/service/customer/CustomerService.java @@ -0,0 +1,33 @@ +package team.marco.voucher_management_system.service.customer; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import team.marco.voucher_management_system.domain.customer.Customer; +import team.marco.voucher_management_system.repository.custromer.CustomerRepository; + +import java.util.List; +import java.util.UUID; + +import static team.marco.voucher_management_system.error.ErrorMessage.CUSTOMER_ID_INVALID; +import static team.marco.voucher_management_system.error.ErrorMessage.INVALID_EMAIL; + +@Transactional(readOnly = true) +@Service +public class CustomerService { + private final CustomerRepository customerRepository; + + public CustomerService(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + public List findAllCustomer() { + return customerRepository.findAll(); + } + + public Customer findCustomerById(UUID customerId) { + return customerRepository.findById(customerId).orElseThrow(() -> new IllegalArgumentException(CUSTOMER_ID_INVALID)); + } + public Customer findCustomerByEmail(String email) { + return customerRepository.findByEmail(email).orElseThrow(() -> new IllegalArgumentException(INVALID_EMAIL)); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/service/voucher/VoucherCreateServiceRequest.java b/src/main/java/team/marco/voucher_management_system/service/voucher/VoucherCreateServiceRequest.java new file mode 100644 index 0000000000..571a42476f --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/service/voucher/VoucherCreateServiceRequest.java @@ -0,0 +1,43 @@ +package team.marco.voucher_management_system.service.voucher; + +import team.marco.voucher_management_system.domain.voucher.VoucherType; + +import java.util.Optional; +import java.util.UUID; + +public class VoucherCreateServiceRequest { + private VoucherType voucherType; + private int discountValue; + private Optional code; + private Optional name; + + public VoucherCreateServiceRequest(VoucherType voucherType, int discountValue, UUID code, String name) { + this.voucherType = voucherType; + this.discountValue = discountValue; + this.code = Optional.ofNullable(code); + this.name = Optional.ofNullable(name); + } + + public VoucherCreateServiceRequest(VoucherType voucherType, int discountValue) { + this.voucherType = voucherType; + this.discountValue = discountValue; + this.code = Optional.empty(); + this.name = Optional.empty(); + } + + public VoucherType getVoucherType() { + return voucherType; + } + + public int getDiscountValue() { + return discountValue; + } + + public Optional getCode() { + return code; + } + + public Optional getName() { + return name; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/service/voucher/VoucherService.java b/src/main/java/team/marco/voucher_management_system/service/voucher/VoucherService.java new file mode 100644 index 0000000000..5b921d77ba --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/service/voucher/VoucherService.java @@ -0,0 +1,47 @@ +package team.marco.voucher_management_system.service.voucher; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; +import team.marco.voucher_management_system.repository.voucher.VoucherRepository; + +import java.util.List; + +@Transactional(readOnly = true) +@Service +public class VoucherService { + private final VoucherRepository voucherRepository; + + public VoucherService(VoucherRepository voucherRepository) { + this.voucherRepository = voucherRepository; + } + + @Transactional + public Voucher createVoucher(VoucherCreateServiceRequest request) { + Long latestId = voucherRepository.findLatestVoucherId().orElse(0L); + + Voucher.Builder builder = new Voucher.Builder(latestId + 1, request.getVoucherType(), request.getDiscountValue()); + request.getCode().ifPresent(code -> builder.code(code)); + request.getName().ifPresent(name -> builder.name(name)); + Voucher voucher = builder.build(); + + return voucherRepository.save(voucher); + } + + public List getVouchers() { + return voucherRepository.findAll(); + } + public List getVouchersByVoucherType(VoucherType type) { + return voucherRepository.findAllByVoucherType(type); + } + + public Voucher getVoucher(Long voucherId) { + return voucherRepository.findById(voucherId).orElseThrow(); + } + + @Transactional + public void deleteVoucher(Long voucherId) { + voucherRepository.deleteById(voucherId); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/util/UUIDUtil.java b/src/main/java/team/marco/voucher_management_system/util/UUIDUtil.java new file mode 100644 index 0000000000..72acb5d4d6 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/util/UUIDUtil.java @@ -0,0 +1,27 @@ +package team.marco.voucher_management_system.util; + +import java.nio.ByteBuffer; +import java.util.UUID; + +public final class UUIDUtil { + private UUIDUtil() { + // Don't let anyone instantiate this class. + } + + public static UUID bytesToUUID(byte[] bytes) { + if(bytes == null) return null; + ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); + return new UUID(byteBuffer.getLong(), byteBuffer.getLong()); + } + + public static UUID stringToUUID(String string) { + return UUID.fromString(string); + } + + public static byte[] uuidToBytes(UUID uuid) { + ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(uuid.getMostSignificantBits()); + byteBuffer.putLong(uuid.getLeastSignificantBits()); + return byteBuffer.array(); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/view/consoleapp/ConsoleUtil.java b/src/main/java/team/marco/voucher_management_system/view/consoleapp/ConsoleUtil.java new file mode 100644 index 0000000000..665f788cd5 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/view/consoleapp/ConsoleUtil.java @@ -0,0 +1,113 @@ +package team.marco.voucher_management_system.view.consoleapp; + +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; +import team.marco.voucher_management_system.controller.customer.dto.CustomerResponse; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherResponse; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.util.List; +import java.util.Objects; + +import static java.text.MessageFormat.format; +import static team.marco.voucher_management_system.error.ErrorMessage.WRONG_INPUT; + +public final class ConsoleUtil { + private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + private static final String INFO_DELIMINATOR = "\n"; + private static final String SEPARATOR_LINE = "--------------------"; + + private ConsoleUtil() { + // Don't let anyone instantiate this class. + } + + public static void print(Object object) { + System.out.println(object); + } + + public static void println() { + System.out.println(); + } + + public static void println(Object object) { + print(object); + println(); + } + + public static String readString() { + System.out.print("> "); + String input = readLine(); + System.out.println(); + + if (Objects.isNull(input)) { + throw new RuntimeException(WRONG_INPUT); + } + + return input; + } + + public static int readInt() { + return Integer.parseInt(readString()); + } + + public static void printStringList(List list) { + String joinedString = String.join(INFO_DELIMINATOR, list); + + if (!joinedString.isBlank()) { + println(joinedString); + } + } + + public static void printCustomerList(List customers) { + customers.forEach(c -> { + printCustomer(c); + printSeparatorLine(); + }); + } + + public static void printCustomerIdAndNameList(List blacklist) { + blacklist.forEach(b -> { + printCustomerIdAndName(b); + printSeparatorLine(); + }); + + } + + public static void printCustomerIdAndName(CustomerIdAndName customerIdAndName) { + print(format("name : {0}", customerIdAndName.getName())); + print(format("id : {0}", customerIdAndName.getId())); + } + + public static void printCustomer(CustomerResponse customer) { + print(format("name : {0}", customer.getName())); + print(format("email : {0}", customer.getEmail())); + print(format("createdAt : {0}", customer.getCreatedAt())); + } + + public static void printVoucherList(List vouchers) { + vouchers.forEach(v -> { + printVoucher(v); + printSeparatorLine(); + }); + } + + public static void printVoucher(VoucherResponse voucher) { + print(format("id : {0}", voucher.getId())); + print(format("name : {0}", voucher.getName())); + print(format("code : {0}", voucher.getCode())); + } + + private static String readLine() { + try { + return reader.readLine(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void printSeparatorLine() { + print(SEPARATOR_LINE); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/view/consoleapp/ConsoleVoucherApplication.java b/src/main/java/team/marco/voucher_management_system/view/consoleapp/ConsoleVoucherApplication.java new file mode 100644 index 0000000000..3c8d19fced --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/view/consoleapp/ConsoleVoucherApplication.java @@ -0,0 +1,109 @@ +package team.marco.voucher_management_system.view.consoleapp; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import team.marco.voucher_management_system.view.consoleapp.management.ManagementApplication; +import team.marco.voucher_management_system.view.consoleapp.wallet.WalletApplication; + +import java.io.UncheckedIOException; + +import static team.marco.voucher_management_system.error.ErrorMessage.*; + +@Component +public class ConsoleVoucherApplication implements Runnable { + private static final Logger logger = LoggerFactory.getLogger(ConsoleVoucherApplication.class); + public static final String MAIN_HEADER = "==== 메인 페이지 ===="; + public static final String SELECT_SERVICE = "Q. 이용하실 서비스를 선택해 주세요."; + public static final String PROGRAM_EXIT = "프로그램이 종료되었습니다."; + + private final WalletApplication walletApplication; + private final ManagementApplication managementApplication; + + private Boolean isRunning; + + public ConsoleVoucherApplication(WalletApplication walletApplication, ManagementApplication managementApplication) { + this.walletApplication = walletApplication; + this.managementApplication = managementApplication; + this.isRunning = false; + } + + @Override + public void run() { + isRunning = true; + + while (isRunning) { + provideLauncher(); + } + } + + private void provideLauncher() { + try { + provideServiceManual(); + ServiceType input = getServiceRequest(); + handleServiceRequest(input); + } catch (Exception e) { + handleException(e); + } + } + + private void provideServiceManual() { + ConsoleUtil.print(MAIN_HEADER); + + for(ServiceType type : ServiceType.values()) { + ConsoleUtil.print(type.getManual()); + } + + ConsoleUtil.println(); + } + + public ServiceType getServiceRequest() { + ConsoleUtil.print(SELECT_SERVICE); + + return ServiceType.get(ConsoleUtil.readInt()); + } + + public void handleServiceRequest(ServiceType requestedServiceType) { + switch (requestedServiceType) { + case MANAGEMENT -> runManagementApplication(); + case WALLET -> runWalletApplication(); + case EXIT -> exit(); + } + } + + private void runManagementApplication() { + managementApplication.run(); + } + + private void runWalletApplication() { + walletApplication.run(); + } + + private void exit() { + logger.info("Call close()"); + + isRunning = false; + ConsoleUtil.print(PROGRAM_EXIT); + } + + private void handleException(Exception e) { + if(e instanceof NumberFormatException) { + ConsoleUtil.print(NUMBER_REQUIRED); + return; + } + + if(e instanceof IllegalArgumentException) { + ConsoleUtil.print(e.getMessage()); + return; + } + + logger.error(e.toString()); + + String errorMessage = (e instanceof UncheckedIOException)? FILE_ERROR : PROGRAM_ERROR; + ConsoleUtil.print(errorMessage); + + isRunning = false; + + exit(); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/view/consoleapp/ServiceType.java b/src/main/java/team/marco/voucher_management_system/view/consoleapp/ServiceType.java new file mode 100644 index 0000000000..166ad471c3 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/view/consoleapp/ServiceType.java @@ -0,0 +1,40 @@ +package team.marco.voucher_management_system.view.consoleapp; + +import java.util.Arrays; + +import static java.text.MessageFormat.format; + +public enum ServiceType { + EXIT(1, "프로그램을 종료합니다."), + MANAGEMENT(2, "관리자 서비스로 이동합니다."), + WALLET(3, "회원 지갑 서비스로 이동합니다."); + + private static final String SERVICE_NOT_EXIST = "해당 서비스가 존재하지 않습니다."; + + private final Integer num; + private final String description; + + ServiceType(Integer num, String description) { + this.num = num; + this.description = description; + } + + static ServiceType get(int num) { + return Arrays.stream(ServiceType.values()) + .filter(v -> isEqual(num, v.getNum())) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(format(SERVICE_NOT_EXIST))); + } + + public Integer getNum() { + return num; + } + + public String getManual() { + return format("{0}. {1}", num, description); + } + + private static Boolean isEqual(int targetNum, int serviceNum) { + return targetNum == serviceNum; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/view/consoleapp/management/ManagementApplication.java b/src/main/java/team/marco/voucher_management_system/view/consoleapp/management/ManagementApplication.java new file mode 100644 index 0000000000..454d92cafa --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/view/consoleapp/management/ManagementApplication.java @@ -0,0 +1,164 @@ +package team.marco.voucher_management_system.view.consoleapp.management; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import team.marco.voucher_management_system.controller.customer.CustomerController; +import team.marco.voucher_management_system.controller.voucher.VoucherController; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherCreateRequest; +import team.marco.voucher_management_system.view.consoleapp.ConsoleUtil; + +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.PERCENT; +import static team.marco.voucher_management_system.error.ErrorMessage.NUMBER_REQUIRED; +import static team.marco.voucher_management_system.error.ErrorMessage.WRONG_INPUT; +import static team.marco.voucher_management_system.view.consoleapp.ConsoleUtil.*; + +@Component +public class ManagementApplication { + private static final Logger logger = LoggerFactory.getLogger(ManagementApplication.class); + public static final String MANAGEMENT_HEADER = "==== 관리자 페이지 ===="; + public static final String SELECT_SERVICE = "Q. 이용하실 서비스를 선택해 주세요."; + public static final String DISCOUNT_PERCENT_REQUEST = "할인율을 입력해 주세요."; + public static final String DISCOUNT_AMOUNT_REQUEST = "할인 금액을 입력해 주세요."; + public static final String VOUCHER_ID_REQUEST = "쿠폰 아이디를 입력해 주세요."; + public static final String VOUCHER_CREATE_COMPLETE = "쿠폰 생성이 완료되었습니다."; + public static final String INQUIRY_COMPLETE = "조회가 완료되었습니다."; + public static final String VOUCHER_MANUAL = """ + 1: $ 할인 쿠폰 + 2: % 할인 쿠폰"""; + + private final VoucherController voucherController; + private final CustomerController customerController; + + private Boolean isRunning; + + public ManagementApplication(VoucherController voucherController, CustomerController customerController) { + this.voucherController = voucherController; + this.customerController = customerController; + this.isRunning = false; + } + + public void run() { + isRunning = true; + + while (isRunning) { + try { + provideCommandManual(); + ManagementCommandType input = getCommandType(); + handleCommand(input); + } catch (Exception e) { + handleException(e); + } + } + } + + public void provideCommandManual() { + print(MANAGEMENT_HEADER); + + for(ManagementCommandType type : ManagementCommandType.values()) { + print(type.getManual()); + } + + println(); + } + + public ManagementCommandType getCommandType() { + print(SELECT_SERVICE); + + return ManagementCommandType.get(readInt()); + } + + public void handleCommand(ManagementCommandType commandType) { + switch (commandType) { + case CREATE_VOUCHER -> createVoucher(); + case VOUCHER_LIST -> getVoucherList(); + case SEARCH_VOUCHER -> getVoucherInfo(); + case CUSTOMER_LIST -> getCustomerList(); + case BLACKLIST -> getBlacklist(); + case BACK -> exit(); + } + } + + private void getCustomerList() { + ConsoleUtil.printCustomerList(customerController.findAll()); + println(); + println(INQUIRY_COMPLETE); + } + + private void getVoucherInfo() { + print(VOUCHER_ID_REQUEST); + String voucherId = readString(); + + printVoucher(voucherController.getVoucher(voucherId)); + println(); + println(INQUIRY_COMPLETE); + } + + private void createVoucher() { + logger.info("Call createVoucher()"); + + print(VOUCHER_MANUAL); + + int selected = readInt(); + + switch (selected) { + case 1 -> createFixedAmountVoucher(); + case 2 -> createPercentDiscountVoucher(); + default -> throw new IllegalArgumentException(WRONG_INPUT); + } + } + + private void createPercentDiscountVoucher() { + logger.info("Call createPercentDiscountVoucher()"); + + print(DISCOUNT_PERCENT_REQUEST); + int percent = readInt(); + + VoucherCreateRequest request = new VoucherCreateRequest(PERCENT, percent); + voucherController.createVoucher(request); + + println(VOUCHER_CREATE_COMPLETE); + } + + private void createFixedAmountVoucher() { + logger.info("Call createFixedAmountVoucher()"); + + print(DISCOUNT_AMOUNT_REQUEST); + int amount = readInt(); + + VoucherCreateRequest request = new VoucherCreateRequest(FIXED, amount); + voucherController.createVoucher(request); + + println(VOUCHER_CREATE_COMPLETE); + } + + private void getVoucherList() { + logger.info("Call getVoucherList()"); + + printVoucherList(voucherController.getVouchers()); + println(); + println(INQUIRY_COMPLETE); + } + + private void getBlacklist() { + logger.info("Call getBlackListUsers()"); + + printCustomerIdAndNameList(customerController.findBlacklist()); + println(); + println(INQUIRY_COMPLETE); + } + + private void exit() { + isRunning = false; + } + + private void handleException(Exception e) { + if(e instanceof NumberFormatException) { + ConsoleUtil.print(NUMBER_REQUIRED); + return; + } + + ConsoleUtil.println(e.getMessage()); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/view/consoleapp/management/ManagementCommandType.java b/src/main/java/team/marco/voucher_management_system/view/consoleapp/management/ManagementCommandType.java new file mode 100644 index 0000000000..8728ffbdfd --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/view/consoleapp/management/ManagementCommandType.java @@ -0,0 +1,41 @@ +package team.marco.voucher_management_system.view.consoleapp.management; + +import java.util.Arrays; + +import static java.text.MessageFormat.format; + +public enum ManagementCommandType { + BACK(1, "메인 페이지로 돌아가기"), + CREATE_VOUCHER(2, "쿠폰 생성"), + VOUCHER_LIST(3, "쿠폰 목록 조회"), + SEARCH_VOUCHER(4, "쿠폰 검색"), + CUSTOMER_LIST(5, "전체 회원 조회"), + BLACKLIST(6, "블랙 리스트 회원 조회"); + + private final Integer num; + private final String description; + + ManagementCommandType(Integer num, String description) { + this.num = num; + this.description = description; + } + + public static ManagementCommandType get(Integer num) { + return Arrays.stream(ManagementCommandType.values()) + .filter(v -> isEqual(num, v.getNum())) + .findAny() + .orElseThrow(); + } + + public int getNum() { + return num; + } + + public String getManual() { + return format("{0}. {1}", num, description); + } + + private static Boolean isEqual(int targetNum, int serviceNum) { + return targetNum == serviceNum; + } +} diff --git a/src/main/java/team/marco/voucher_management_system/view/consoleapp/wallet/WalletApplication.java b/src/main/java/team/marco/voucher_management_system/view/consoleapp/wallet/WalletApplication.java new file mode 100644 index 0000000000..140a67f6e9 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/view/consoleapp/wallet/WalletApplication.java @@ -0,0 +1,120 @@ +package team.marco.voucher_management_system.view.consoleapp.wallet; + +import org.springframework.stereotype.Component; +import team.marco.voucher_management_system.controller.customer.CustomerController; +import team.marco.voucher_management_system.controller.voucher.VoucherController; +import team.marco.voucher_management_system.domain.customer.Customer; +import team.marco.voucher_management_system.view.consoleapp.ConsoleUtil; + +import java.util.UUID; + +import static team.marco.voucher_management_system.error.ErrorMessage.CUSTOMER_ID_INVALID; +import static team.marco.voucher_management_system.error.ErrorMessage.NUMBER_REQUIRED; +import static team.marco.voucher_management_system.view.consoleapp.ConsoleUtil.*; + +@Component +public class WalletApplication { + public static final String CUSTOMER_EMAIL_REQUEST = "사용자 이메일을 입력해주세요."; + public static final String WALLET_HEADER = "==== 지갑 페이지 ===="; + public static final String SELECT_SERVICE = "Q. 이용하실 서비스를 선택해 주세요."; + public static final String VOUCHER_ID_REQUEST = "쿠폰 번호를 입력해 주세요."; + public static final String VOUCHER_DELETE_COMPLETE = "쿠폰 삭제가 완료되었습니다."; + // Preparing for service + private static final String PREPARING_FOR_SERVICE = "현재 지갑 서비스를 준비 중입니다."; + + private final VoucherController voucherController; + private final CustomerController customerController; + + private Boolean isRunning; + private UUID customerId; + + public WalletApplication(VoucherController voucherController, CustomerController customerController) { + this.voucherController = voucherController; + this.customerController = customerController; + this.isRunning = false; + } + + public void run() { + print(PREPARING_FOR_SERVICE); + println(); + +// isRunning = true; +// customerId = validateCustomer(); +// +// while (isRunning) { +// try { +// provideCommandManual(); +// WalletCommandType input = getCommandType(); +// handleCommand(input); +// } catch (IllegalArgumentException e) { +// handleException(e); +// } +// } + } + + private UUID validateCustomer() { + ConsoleUtil.print(CUSTOMER_EMAIL_REQUEST); + String customerEmail = ConsoleUtil.readString(); + + Customer customer = customerController.findCustomerByEmail(customerEmail); + + if(customer == null) { + throw new IllegalArgumentException(CUSTOMER_ID_INVALID); + } + return customer.getId(); + } + + public void provideCommandManual() { + print(WALLET_HEADER); + + for(WalletCommandType type : WalletCommandType.values()) { + print(type.getManual()); + } + + println(); + } + + public WalletCommandType getCommandType() { + print(SELECT_SERVICE); + + return WalletCommandType.get(readInt()); + } + + public void handleCommand(WalletCommandType commandType) { + switch (commandType) { + case REGISTER -> registerVoucher(customerId); + case LIST -> getMyVouchers(customerId); + case REMOVE -> removeVoucher(); + case BACK -> backToMainApplication(); + } + } + + private void getMyVouchers(UUID customerId) { + // TODO + } + + private void registerVoucher(UUID customerId) { + // TODO + } + + private void removeVoucher() { + ConsoleUtil.print(VOUCHER_ID_REQUEST); + String voucherId = ConsoleUtil.readString(); + voucherController.deleteVoucher(voucherId); + + ConsoleUtil.print(VOUCHER_DELETE_COMPLETE); + } + + private void backToMainApplication() { + isRunning = false; + } + + private void handleException(Exception e) { + if(e instanceof NumberFormatException) { + ConsoleUtil.print(NUMBER_REQUIRED); + return; + } + + ConsoleUtil.println(e.getMessage()); + } +} diff --git a/src/main/java/team/marco/voucher_management_system/view/consoleapp/wallet/WalletCommandType.java b/src/main/java/team/marco/voucher_management_system/view/consoleapp/wallet/WalletCommandType.java new file mode 100644 index 0000000000..f2cd868052 --- /dev/null +++ b/src/main/java/team/marco/voucher_management_system/view/consoleapp/wallet/WalletCommandType.java @@ -0,0 +1,39 @@ +package team.marco.voucher_management_system.view.consoleapp.wallet; + +import java.util.Arrays; + +import static java.text.MessageFormat.format; + +public enum WalletCommandType { + BACK(1, "메인 페이지로 돌아가기"), + REGISTER(2, "쿠폰 등록"), + LIST(3, "나의 쿠폰 목록 조회"), + REMOVE(4, "쿠폰 삭제"); + + private final int num; + private final String description; + + WalletCommandType(int num, String description) { + this.num = num; + this.description = description; + } + + public static WalletCommandType get(int num) { + return Arrays.stream(WalletCommandType.values()) + .filter(v -> isEqual(num, v.getNum())) + .findAny() + .orElseThrow(); + } + + public int getNum() { + return num; + } + + public String getManual() { + return format("{0}. {1}", num, description); + } + + private static Boolean isEqual(int targetNum, int serviceNum) { + return targetNum == serviceNum; + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000000..0cca9935aa --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,12 @@ +# application-dav.yml +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3305/voucher_mgmt_system?serverTimezone=Asia/Seoul&characterEncoding=UTF-8 + username: root + password: uijin-mysql-pw + +file: + path: + blacklist: "src/main/resources/data/blacklist.csv" + voucher_data: "src/main/resources/data/voucher_data.json" \ No newline at end of file diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000000..fd00dee326 --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,11 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3305/voucher_mgmt_system?serverTimezone=Asia/Seoul&characterEncoding=UTF-8 + username: root + password: uijin-mysql-pw + +file: + path: + blacklist: "src/main/resources/data/blacklist.csv" + voucher_data: "src/main/resources/data/voucher_data.json" \ No newline at end of file diff --git a/src/main/resources/application-test.yml b/src/main/resources/application-test.yml new file mode 100644 index 0000000000..39108f691f --- /dev/null +++ b/src/main/resources/application-test.yml @@ -0,0 +1,11 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3305/test_voucher_mgmt_system?serverTimezone=Asia/Seoul&characterEncoding=UTF-8 + username: root + password: uijin-mysql-pw + +file: + path: + blacklist: "src/test/resources/test_blacklist.csv" + voucher_data: "src/test/resources/test_voucher_data.json" \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000000..f92c3839ea --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,14 @@ +application: + title: "voucher-management-system" + version: "1.0.0" + +spring: + profiles: + default: prod + + thymeleaf: + cache: false + check-template-location: false + enabled: true + + mvc.hiddenmethod.filter.enabled: true \ No newline at end of file diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 0000000000..46f6b39b4a --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,7 @@ + ___ ___ __ _______ __ __ __ __ +| | |.-----.--.--.----.| |--.-----.----. | _ |.-----.-----.| |__|.----.---.-.| |_|__|.-----.-----. +| | || _ | | | __|| | -__| _| | || _ | _ || | || __| _ || _| || _ | | + \_____/ |_____|_____|____||__|__|_____|__| |___|___|| __| __||__|__||____|___._||____|__||_____|__|__| + |__| |__| +${application.title} ${application.version} +Powered by Spring Boot ${spring-boot.version} diff --git a/src/main/resources/data/blacklist.csv b/src/main/resources/data/blacklist.csv new file mode 100644 index 0000000000..3f6a9afedd --- /dev/null +++ b/src/main/resources/data/blacklist.csv @@ -0,0 +1,3 @@ +id,name +461b8847-578d-43c7-8472-d9374bbac41a,정의진 +461b8847-578d-43c7-8472-d9374bbac42b,김현우 diff --git a/src/main/resources/data/data.sql b/src/main/resources/data/data.sql new file mode 100644 index 0000000000..3a181166f3 --- /dev/null +++ b/src/main/resources/data/data.sql @@ -0,0 +1,4 @@ +# Customers 테스트 데이터 삽입 +INSERT INTO customers(customer_id, name, email) VALUES (UUID_TO_BIN(UUID()), '정의진', '정의진@gmail.com'); +INSERT INTO customers(customer_id, name, email) VALUES (UUID_TO_BIN(UUID()), '김현우', '김현우@gmail.com'); +INSERT INTO customers(customer_id, name, email) VALUES (UUID_TO_BIN(UUID()), '이세희', '이세희@gmail.com'); diff --git a/src/main/resources/data/sample_data.json b/src/main/resources/data/sample_data.json new file mode 100644 index 0000000000..91b4aacec6 --- /dev/null +++ b/src/main/resources/data/sample_data.json @@ -0,0 +1,16 @@ +[ + { + "code": "5e144cb9-b51c-4b10-97f4-f2402479ae06", + "discountValue": 1000, + "id": 2, + "name": "1,000원 할인 쿠폰", + "voucherType": "FIXED" + }, + { + "code": "6bfbb93a-0337-4d1e-bb39-d761052b321a", + "discountValue": 60, + "id": 3, + "name": "60% 할인 쿠폰", + "voucherType": "PERCENT" + } +] diff --git a/src/main/resources/data/schema.sql b/src/main/resources/data/schema.sql new file mode 100644 index 0000000000..011015170e --- /dev/null +++ b/src/main/resources/data/schema.sql @@ -0,0 +1,53 @@ +DROP DATABASE IF EXISTS voucher_mgmt_system; +DROP DATABASE IF EXISTS test_voucher_mgmt_system; + +CREATE DATABASE voucher_mgmt_system; +CREATE DATABASE test_voucher_mgmt_system; + +USE voucher_mgmt_system; + +DROP TABLE IF EXISTS vouchers; +DROP TABLE IF EXISTS customers; + +CREATE TABLE customers ( + customer_id BINARY(16) NOT NULL, + name VARCHAR(20) NOT NULL, + email VARCHAR(50) NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_customer_id PRIMARY KEY (customer_id), + CONSTRAINT unq_customer_email UNIQUE KEY (email) +); + +CREATE TABLE `vouchers` ( + voucher_id BIGINT NOT NULL, + voucher_type ENUM('FIXED','PERCENT') NOT NULL, + discount_value INTEGER NOT NULL, + code BINARY(16) NOT NULL, + name VARCHAR(50) DEFAULT NULL, + CONSTRAINT pk_voucher_id PRIMARY KEY (voucher_id), + CONSTRAINT unq_code UNIQUE KEY (code) +); + +USE test_voucher_mgmt_system; + +DROP TABLE IF EXISTS vouchers; +DROP TABLE IF EXISTS customers; + +CREATE TABLE customers ( + customer_id BINARY(16) NOT NULL, + name VARCHAR(20) NOT NULL, + email VARCHAR(50) NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_customer_id PRIMARY KEY (customer_id), + CONSTRAINT unq_customer_email UNIQUE KEY (email) +); + +CREATE TABLE `vouchers` ( + voucher_id BIGINT NOT NULL, + voucher_type ENUM('FIXED','PERCENT') NOT NULL, + discount_value INTEGER NOT NULL, + code BINARY(16) NOT NULL, + name VARCHAR(50) DEFAULT NULL, + CONSTRAINT pk_voucher_id PRIMARY KEY (voucher_id), + CONSTRAINT unq_code UNIQUE KEY (code) +); diff --git a/src/main/resources/data/voucher_data.json b/src/main/resources/data/voucher_data.json new file mode 100644 index 0000000000..0637a088a0 --- /dev/null +++ b/src/main/resources/data/voucher_data.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000000..360548a302 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,42 @@ + + + + + + + ${LOG_PATTERN} + + + + + logs/access.log + + logs/access-%d{yyyy-MM-dd}.log + + + ${LOG_PATTERN} + + + + + logs/error.log + + logs/error-%d{yyyy-MM-dd}.log + + + ${LOG_PATTERN} + + + + + + + + + + + + + + + diff --git a/src/main/resources/templates/layouts/aside.html b/src/main/resources/templates/layouts/aside.html new file mode 100644 index 0000000000..53d8de8f1a --- /dev/null +++ b/src/main/resources/templates/layouts/aside.html @@ -0,0 +1,14 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/layouts/footer.html b/src/main/resources/templates/layouts/footer.html new file mode 100644 index 0000000000..5325462481 --- /dev/null +++ b/src/main/resources/templates/layouts/footer.html @@ -0,0 +1,14 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/layouts/layout.html b/src/main/resources/templates/layouts/layout.html new file mode 100644 index 0000000000..881f0eda16 --- /dev/null +++ b/src/main/resources/templates/layouts/layout.html @@ -0,0 +1,129 @@ + + + + + + + + + + +
+ + + +
+
+ +
+
+
+
+ + diff --git a/src/main/resources/templates/voucher/voucher_create_form.html b/src/main/resources/templates/voucher/voucher_create_form.html new file mode 100644 index 0000000000..bfe9e92029 --- /dev/null +++ b/src/main/resources/templates/voucher/voucher_create_form.html @@ -0,0 +1,30 @@ + + + + +
+
+ # 쿠폰 생성 +
+
+
+
+
+ + $ 할인 쿠폰 + % 할인 쿠폰
+
+
+ + +
+
+ +
+
+
+
+ \ No newline at end of file diff --git a/src/main/resources/templates/voucher/voucher_detail.html b/src/main/resources/templates/voucher/voucher_detail.html new file mode 100644 index 0000000000..095a96ee67 --- /dev/null +++ b/src/main/resources/templates/voucher/voucher_detail.html @@ -0,0 +1,30 @@ + + + + +
+
+ # 쿠폰 목록 +
+
+
+
+ + + + + + + + + + + +
ID쿠폰명쿠폰 코드
+
+
+
+ \ No newline at end of file diff --git a/src/main/resources/templates/voucher/voucher_list.html b/src/main/resources/templates/voucher/voucher_list.html new file mode 100644 index 0000000000..e2e74db08f --- /dev/null +++ b/src/main/resources/templates/voucher/voucher_list.html @@ -0,0 +1,41 @@ + + + +
+
+ # 쿠폰 목록 +
+
+ +
+
+ + + + + + + + + + + + + + + +
ID쿠폰명쿠폰 코드
+ + +
+ + +
+
+
+
+
+ diff --git a/src/test/java/team/marco/voucher_management_system/controller/customer/CustomerControllerTest.java b/src/test/java/team/marco/voucher_management_system/controller/customer/CustomerControllerTest.java new file mode 100644 index 0000000000..4cca5aa09d --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/controller/customer/CustomerControllerTest.java @@ -0,0 +1,113 @@ +package team.marco.voucher_management_system.controller.customer; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; +import team.marco.voucher_management_system.controller.customer.dto.CustomerResponse; +import team.marco.voucher_management_system.domain.customer.Customer; +import team.marco.voucher_management_system.service.customer.BlacklistService; +import team.marco.voucher_management_system.service.customer.CustomerService; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@WebMvcTest(controllers = CustomerController.class) +class CustomerControllerTest { + @MockBean + private CustomerService customerService; + + @MockBean + private BlacklistService blacklistService; + + private CustomerController customerController; + + @BeforeEach + void setup() { + this.customerController = new CustomerController(customerService, blacklistService); + } + + @DisplayName("블랙리스트 사용자를 조회할 수 있다.") + @Test + void getBlacklistInfo() { + // given + List blacklist = new ArrayList<>(); + + when(blacklistService.getBlacklist()).thenReturn(blacklist); + + // when + List result = customerController.findBlacklist(); + + // then + assertThat(result).isNotNull(); + } + + @DisplayName("사용자 ID로 존재하는 사용자인지 확인할 수 있다.") + @Test + void isExistCustomerWhenExist() { + // given + Customer customer = new Customer.Builder("name", "email@gmail.com").build(); + when(customerService.findCustomerById(customer.getId())).thenReturn(customer); + + // when + boolean result = customerController.isExistCustomer(customer.getId().toString()); + + // then + assertThat(result).isTrue(); + } + + @DisplayName("존재하지 않는 사용자가 존재하는지 요청하면 확인할 수 있다.") + @Test + void isExistCustomerWhenNotExist() { + // given + Customer customer = new Customer.Builder("name", "email@gmail.com").build(); + when(customerService.findCustomerById(customer.getId())).thenThrow(NoSuchElementException.class); + + // when + boolean result = customerController.isExistCustomer(customer.getId().toString()); + + // then + assertThat(result).isFalse(); + } + + @DisplayName("전체 사용자 목록을 확인할 수 있습니다.") + @Test + void findAll() { + // given + Customer customer = new Customer.Builder("name", "email@gmail.com").build(); + List customers = new ArrayList<>(); + customers.add(customer); + + when(customerService.findAllCustomer()).thenReturn(customers); + + // when + List result = customerController.findAll(); + + // then + assertThat(result).hasSize(1); + assertThat(result.get(0)) + .extracting("name", "email") + .containsExactly(customer.getName(), customer.getEmail()); + } + + @DisplayName("사용자 이메일로 사용자를 조회할 수 있다.") + @Test + void findCustomerByEmail() { + // given + String email = "email@gmail.com"; + Customer customer = new Customer.Builder("name", email).build(); + when(customerService.findCustomerByEmail(email)).thenReturn(customer); + + // when + Customer found = customerController.findCustomerByEmail(email); + + // then + assertThat(found).isNotNull(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherApiControllerTest.java b/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherApiControllerTest.java new file mode 100644 index 0000000000..a5769a7000 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherApiControllerTest.java @@ -0,0 +1,125 @@ +package team.marco.voucher_management_system.controller.voucher; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherCreateRequest; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; +import team.marco.voucher_management_system.service.voucher.VoucherService; + +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; + +@WebMvcTest(controllers = VoucherApiController.class) +class VoucherApiControllerTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @MockBean + private VoucherService voucherService; + + @DisplayName("전체 쿠폰 목록을 조회할 수 있다.") + @Test + void findAllVouchers() throws Exception { + // given + List vouchers = new ArrayList<>(); + + when(voucherService.getVouchers()).thenReturn(vouchers); + + // when then + mockMvc.perform( + get("/api/vouchers") + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value("200")) + .andExpect(jsonPath("$.status").value("OK")) + .andExpect(jsonPath("$.message").value("OK")) + .andExpect(jsonPath("$.data").isArray()); + } + + @DisplayName("쿠폰 유형을 넘기면 해당 유형의 쿠폰 목록을 조회할 수 있다.") + @Test + void findAllVouchersWithVoucherType() throws Exception { + // given + VoucherType voucherType = FIXED; + List vouchers = new ArrayList<>(); + + when(voucherService.getVouchers()).thenReturn(vouchers); + + // when then + mockMvc.perform( + get("/api/vouchers") + .param("voucherType", voucherType.name()) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value("200")) + .andExpect(jsonPath("$.status").value("OK")) + .andExpect(jsonPath("$.message").value("OK")) + .andExpect(jsonPath("$.data").isArray()); + } + + @DisplayName("쿠폰 ID로 쿠폰 상세 정보를 조회할 수 있다.") + @Test + void getVoucher() throws Exception { + // given + Voucher voucher = new Voucher.Builder(1L, FIXED, 1_000).build(); + + when(voucherService.getVoucher(voucher.getId())).thenReturn(voucher); + + // when then + mockMvc.perform( + get("/api/vouchers/{voucherId}", 1L) + ) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value("200")) + .andExpect(jsonPath("$.status").value("OK")) + .andExpect(jsonPath("$.message").value("OK")) + .andExpect(jsonPath("$.data.id").value(voucher.getId())) + .andExpect(jsonPath("$.data.code").value(voucher.getCode().toString())) + .andExpect(jsonPath("$.data.name").value(voucher.getName())); + } + + @DisplayName("쿠폰을 생성할 수 있다.") + @Test + void createVoucher() throws Exception { + // given + VoucherCreateRequest request = new VoucherCreateRequest(FIXED, 1000); + Voucher voucher = new Voucher.Builder(1L, FIXED, 1000).build(); + when(voucherService.createVoucher(any())).thenReturn(voucher); + + // when then + mockMvc.perform( + post("/api/vouchers") + .content(objectMapper.writeValueAsString(request)) + .contentType(MediaType.APPLICATION_JSON) + ).andExpect(status().isOk()); + } + + @DisplayName("쿠폰 ID로 쿠폰을 삭제할 수 있다.") + @Test + void deleteVoucher() throws Exception { + // given + Long voucherId = 1L; + + // when + mockMvc.perform( + delete("/api/vouchers/{voucherId}", voucherId) + ).andExpect(status().isOk()).andReturn(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherControllerTest.java b/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherControllerTest.java new file mode 100644 index 0000000000..eb1afa3b19 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherControllerTest.java @@ -0,0 +1,103 @@ +package team.marco.voucher_management_system.controller.voucher; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherCreateRequest; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherResponse; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.service.voucher.VoucherCreateServiceRequest; +import team.marco.voucher_management_system.service.voucher.VoucherService; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.when; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; + +@WebMvcTest(controllers = VoucherController.class) +class VoucherControllerTest { + @MockBean + private VoucherService voucherService; + private VoucherController voucherController; + + @BeforeEach + void setup() { + this.voucherController = new VoucherController(voucherService); + } + + @DisplayName("쿠폰을 생성할 수 있다.") + @Test + void createVoucher() { + // given + VoucherCreateRequest request = new VoucherCreateRequest(FIXED, 1_000); + VoucherCreateServiceRequest serviceRequest = request.toServiceRequest(); + Voucher voucher = new Voucher.Builder(1L, request.getVoucherType(), request.getDiscountValue()).build(); + + when(voucherService.createVoucher(serviceRequest)).thenReturn(voucher); + + // when + voucherController.createVoucher(request); + + // then + assertThatNoException(); + } + + @DisplayName("discountValue가 0이하인 쿠폰 생성 요청은 할 수 없다.") + @Test + void createVoucherWithZeroDiscountValue() { + // given + int zero = 0; + + // when then + assertThatThrownBy(() -> voucherController.createVoucher( + new VoucherCreateRequest(FIXED, zero))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("할인 금액 또는 할인율은 양수입니다."); + } + + @DisplayName("쿠폰 ID로 쿠폰을 조회할 수 있다.") + @Test + void getVoucher() { + // given + Voucher voucher = new Voucher.Builder(1L, FIXED, 1_000).build(); + + when(voucherService.getVoucher(voucher.getId())).thenReturn(voucher); + + // when + VoucherResponse response = voucherController.getVoucher("1"); + + // then + assertThat(response) + .extracting("id", "code", "name") + .containsExactly(1L, voucher.getCode(), voucher.getName()); + } + + @DisplayName("전체 쿠폰 목록을 조회할 수 있다.") + @Test + void getVouchers() { + // given + List vouchers = new ArrayList<>(); + + when(voucherService.getVouchers()).thenReturn(vouchers); + + // when + List response = voucherController.getVouchers(); + + // then + assertThat(response).isNotNull(); + } + + @DisplayName("쿠폰 ID로 쿠폰을 삭제할 수 있다.") + @Test + void deleteVoucher() { + // when + voucherController.deleteVoucher("1"); + + // then + assertThatNoException(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherViewControllerTest.java b/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherViewControllerTest.java new file mode 100644 index 0000000000..30f02865a9 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/controller/voucher/VoucherViewControllerTest.java @@ -0,0 +1,114 @@ +package team.marco.voucher_management_system.controller.voucher; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.ModelAndViewAssert; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.web.servlet.ModelAndView; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.service.voucher.VoucherService; + +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; + +@WebMvcTest(controllers = VoucherViewController.class) +class VoucherViewControllerTest { + @Autowired + private MockMvc mockMvc; + + @MockBean + private VoucherService voucherService; + + @DisplayName("전체 쿠폰 목록을 조회할 수 있다.") + @Test + void findAllVouchers() throws Exception { + // given + List vouchers = new ArrayList<>(); + + when(voucherService.getVouchers()).thenReturn(vouchers); + + // when + MvcResult mvcResult = mockMvc.perform( + get("/vouchers") + ).andExpect(status().isOk()).andReturn(); + + // then + ModelAndView modelAndView = mvcResult.getModelAndView(); + ModelAndViewAssert.assertViewName(modelAndView, "voucher/voucher_list"); + } + + @DisplayName("쿠폰 ID로 쿠폰 상세 정보를 조회할 수 있다.") + @Test + void findVoucher() throws Exception { + // given + Voucher voucher = new Voucher.Builder(1L, FIXED, 1_000).build(); + + when(voucherService.getVoucher(voucher.getId())).thenReturn(voucher); + + // when + MvcResult mvcResult = mockMvc.perform( + get("/vouchers/{voucherId}", 1L) + ).andExpect(status().isOk()).andReturn(); + + // then + ModelAndView modelAndView = mvcResult.getModelAndView(); + ModelAndViewAssert.assertViewName(modelAndView, "voucher/voucher_detail"); + } + + @DisplayName("쿠폰 생성 폼 뷰 html 파일을 제공할 수 있다.") + @Test + void findVoucherCreateForm() throws Exception { + // when + MvcResult mvcResult = mockMvc.perform( + get("/vouchers/create") + ).andExpect(status().isOk()).andReturn(); + + // then + ModelAndView modelAndView = mvcResult.getModelAndView(); + ModelAndViewAssert.assertViewName(modelAndView, "voucher/voucher_create_form"); + } + + @DisplayName("쿠폰을 생성할 수 있다.") + @Test + void createVoucher() throws Exception { + // given + String voucherType = FIXED.name(); + int discountValue = 1_000; + + // when + MvcResult mvcResult = mockMvc.perform( + post("/vouchers") + .param("voucherType", voucherType) + .param("discountValue", String.valueOf(discountValue)) + ).andExpect(status().isOk()).andReturn(); + + // then + ModelAndView modelAndView = mvcResult.getModelAndView(); + ModelAndViewAssert.assertViewName(modelAndView, "voucher/voucher_list"); + } + + @DisplayName("쿠폰 ID로 쿠폰을 삭제할 수 있다.") + @Test + void deleteVoucher() throws Exception { + // given + Long voucherId = 1L; + + // when + MvcResult mvcResult = mockMvc.perform( + delete("/vouchers/{voucherId}", voucherId) + ).andExpect(status().isOk()).andReturn(); + + // then + ModelAndView modelAndView = mvcResult.getModelAndView(); + ModelAndViewAssert.assertViewName(modelAndView, "voucher/voucher_list"); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/domain/customer/CustomerTest.java b/src/test/java/team/marco/voucher_management_system/domain/customer/CustomerTest.java new file mode 100644 index 0000000000..7bb8dd6302 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/domain/customer/CustomerTest.java @@ -0,0 +1,63 @@ +package team.marco.voucher_management_system.domain.customer; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CustomerTest { + + @DisplayName("필수값(이름, 이메일)만으로 사용자를 생성할 수 있다.") + @Test + void createCustomerByBuilder() { + // given + String name = "name"; + String email = "email@gmail.com"; + + // when + Customer customer = new Customer.Builder(name, email).build(); + + // then + assertThat(customer.getId()).isNotNull(); + assertThat(customer.getCreatedAt()).isNotNull(); + assertThat(customer) + .extracting("name", "email") + .contains(name, email); + } + + @DisplayName("사용자 ID는 중복되지 않는다.") + @Test + void createUniqueIdWhenUserCreate() { + // given // when + Customer customer1 = new Customer.Builder("name1", "email1@gmail.com").build(); + Customer customer2 = new Customer.Builder("name2", "email2@gmail.com").build(); + + // then + assertThat(customer1.getId()).isNotEqualTo(customer2.getId()); + } + + @DisplayName("사용자 이름은 빈칸 혹은 공백일 수 없다.") + @Test + void createCustomerWithBlankName() { + // given // when + String blankName = " "; + + // then when + assertThatThrownBy(() -> new Customer.Builder(blankName, "email1@gmail.com").build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("빈 문자열 일 수 없습니다."); + } + + @DisplayName("사용자 이메일은 빈칸 혹은 공백일 수 없다.") + @Test + void createCustomerWithBlankEmail() { + // given // when + String blankEmail = " "; + + // then when + assertThatThrownBy(() -> new Customer.Builder("name", blankEmail).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("빈 문자열 일 수 없습니다."); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/domain/voucher/VoucherTest.java b/src/test/java/team/marco/voucher_management_system/domain/voucher/VoucherTest.java new file mode 100644 index 0000000000..dd945b452c --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/domain/voucher/VoucherTest.java @@ -0,0 +1,86 @@ +package team.marco.voucher_management_system.domain.voucher; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.*; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.PERCENT; + +class VoucherTest { + + @DisplayName("필수값만(아이디, 쿠폰 종류, 할인값)으로 쿠폰을 생성할 수 있다.") + @Test + void createVoucherByBuilder() { + // given + Long id = 1L; + VoucherType voucherType = FIXED; + int discountValue = 10_000; + + // when + Voucher voucher = new Voucher.Builder(id, voucherType, discountValue).build(); + + // then + assertThat(voucher) + .extracting("id", "voucherType", "discountValue") + .contains(id, voucherType, discountValue); + assertThat(voucher.getCode()).isNotNull(); + assertThat(voucher.getName()).isEqualTo("10,000원 할인 쿠폰"); + } + + @DisplayName("고정 금액 쿠폰은 1,000원이상 할인해야 합니다.") + @Test + void createFixedVoucherWithMinValue() { + // given + int lessAmount = 990; + int minAmount = 1_000; + + // when then + assertThatNoException().isThrownBy(() -> new Voucher.Builder(1L, FIXED, minAmount).build()); + assertThatThrownBy(() -> new Voucher.Builder(2L, FIXED, lessAmount).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("할인 금액은 1,000원 이상, 100,000원 이하이어야 합니다."); + } + + @DisplayName("고정 금액 쿠폰은 10만원이하로 할인해야 합니다.") + @Test + void createFixedVoucherWithMaxValue() { + // given + int tooMuchAmount = 1000_010; + int maxAmount = 100_000; + + // when then + assertThatNoException().isThrownBy(() -> new Voucher.Builder(1L, FIXED, maxAmount).build()); + assertThatThrownBy(() -> new Voucher.Builder(2L, FIXED, tooMuchAmount).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("할인 금액은 1,000원 이상, 100,000원 이하이어야 합니다."); + } + + @DisplayName("% 할인 쿠폰은 5% 이상 할인해야 합니다.") + @Test + void createPercentVoucherWithMinValue() { + // given + int lessPercent = 4; + int minPercent = 5; + + // when then + assertThatNoException().isThrownBy(() -> new Voucher.Builder(1L, PERCENT, minPercent).build()); + assertThatThrownBy(() -> new Voucher.Builder(2L, PERCENT, lessPercent).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("할인 비율은 5% 이상, 100% 이하이어야 합니다."); + } + + @DisplayName("% 할인 쿠폰은 100% 이하로 할인해야 합니다.") + @Test + void createPercentVoucherWithMaxValue() { + // given + int tooMuchPercent = 101; + int maxPercent = 100; + + // when then + assertThatNoException().isThrownBy(() -> new Voucher.Builder(1L, PERCENT, maxPercent).build()); + assertThatThrownBy(() -> new Voucher.Builder(2L, PERCENT, tooMuchPercent).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("할인 비율은 5% 이상, 100% 이하이어야 합니다."); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/repository/custromer/CsvBlacklistRepositoryTest.java b/src/test/java/team/marco/voucher_management_system/repository/custromer/CsvBlacklistRepositoryTest.java new file mode 100644 index 0000000000..e48681694c --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/repository/custromer/CsvBlacklistRepositoryTest.java @@ -0,0 +1,48 @@ +package team.marco.voucher_management_system.repository.custromer; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.groups.Tuple.tuple; +import static team.marco.voucher_management_system.util.UUIDUtil.stringToUUID; + +@SpringBootTest +@ActiveProfiles("test") +class CsvBlacklistRepositoryTest { + private CsvBlacklistRepository csvBlacklistRepository; + + public CsvBlacklistRepositoryTest(@Value("${file.path.blacklist}") String path) { + csvBlacklistRepository = new CsvBlacklistRepository(path); + } + + @DisplayName("파일에 저장된 사용자 블랙리스트를 조회할 수 있습니다.") + @Test + void findAll() { + /** + * test_blacklist.csv에 + * id name + * 461b8847-578d-43c7-8472-d9374bbac41a 정의진 + * 461b8847-578d-43c7-8472-d9374bbac42b 김현우 + * 를 미리 넣어 놨습니다. + */ + + // when + List blacklist = csvBlacklistRepository.findAll(); + + // then + assertThat(blacklist).hasSize(2); + assertThat(blacklist) + .extracting("id", "name") + .containsExactlyInAnyOrder( + tuple(stringToUUID("461b8847-578d-43c7-8472-d9374bbac41a"), "정의진"), + tuple(stringToUUID("461b8847-578d-43c7-8472-d9374bbac42b"), "김현우") + ); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/repository/custromer/JdbcCustomerRepositoryTest.java b/src/test/java/team/marco/voucher_management_system/repository/custromer/JdbcCustomerRepositoryTest.java new file mode 100644 index 0000000000..cafd20e113 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/repository/custromer/JdbcCustomerRepositoryTest.java @@ -0,0 +1,123 @@ +package team.marco.voucher_management_system.repository.custromer; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ActiveProfiles; +import team.marco.voucher_management_system.domain.customer.Customer; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@SpringBootTest +@ActiveProfiles("test") +class JdbcCustomerRepositoryTest { + @Autowired + private JdbcCustomerRepository customerRepository; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @BeforeEach + void setUp() { + String query = "DELETE FROM customers"; + jdbcTemplate.update(query); + } + + @DisplayName("사용자를 생성할 수 있습니다.") + @Test + void insert() { + // given + String name = "customer"; + String email = "customer@gmail.com"; + Customer customer = createCustomer(name, email); + + // when + Customer saved = customerRepository.insert(customer); + + // then + // UUID와 생성 시간은 주어지지 않으면 자동으로 들어감 + Assertions.assertThat(saved.getId()).isNotNull(); + Assertions.assertThat(saved.getCreatedAt()).isNotNull(); + Assertions.assertThat(saved.getId()).isEqualTo(customer.getId()); + } + + @DisplayName("동일한 이메일을 가진 유저는 생성할 수 없습니다.") + @Test + void insertWithDuplicateEmail() { + // given + String name = "customer"; + String email = "customer@gmail.com"; + Customer customer = createCustomer(name, email); + customerRepository.insert(customer); + + String name2 = "customer2"; + String sameEmail = "customer@gmail.com"; + Customer wrongCustomer = createCustomer(name2, sameEmail); + + // when then + assertThrows(DuplicateKeyException.class, + () -> customerRepository.insert(wrongCustomer)); + } + + @DisplayName("전체 사용자 목록을 조회할 수 있습니다.") + @Test + void findAll() { + // given + Customer customer = createCustomer("customer", "customer@gmail.com"); + Customer customer2 = createCustomer("customer2", "customer2@gmail.com"); + customerRepository.insert(customer); + customerRepository.insert(customer2); + + // when + List customers = customerRepository.findAll(); + + // then + assertThat(customers).hasSize(2); + } + + @DisplayName("사용자 아이디로 사용자를 조회할 수 있습니다.") + @Test + void findById() { + // given + String name = "customer"; + String email = "customer@gmail.com"; + Customer customer = createCustomer(name, email); + customerRepository.insert(customer); + + // when + Customer found = customerRepository.findById(customer.getId()).get(); + + // then + Assertions.assertThat(found.getId()).isEqualTo(customer.getId()); + } + + @DisplayName("사용자 이메일로 사용자를 조회할 수 있다.") + @Test + void findByEmail() { + // given + String name = "customer"; + String email = "customer@gmail.com"; + Customer customer = createCustomer(name, email); + customerRepository.insert(customer); + + // when + Customer found = customerRepository.findByEmail("customer@gmail.com").get(); + + // then + Assertions.assertThat(found.getId()).isEqualTo(customer.getId()); + } + + private Customer createCustomer(String name, String email) { + return new Customer + .Builder(name, email) + .build(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/repository/voucher/JdbcVoucherRepositoryTest.java b/src/test/java/team/marco/voucher_management_system/repository/voucher/JdbcVoucherRepositoryTest.java new file mode 100644 index 0000000000..8acc98eacf --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/repository/voucher/JdbcVoucherRepositoryTest.java @@ -0,0 +1,146 @@ +package team.marco.voucher_management_system.repository.voucher; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ActiveProfiles; +import team.marco.voucher_management_system.domain.voucher.Voucher; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.PERCENT; + +@SpringBootTest +@ActiveProfiles("test") +class JdbcVoucherRepositoryTest { + @Autowired + private JdbcVoucherRepository voucherRepository; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @BeforeEach + void setUp() { + String query = "DELETE FROM vouchers"; + jdbcTemplate.update(query); + } + + @Test + @DisplayName("바우처 생성 시 생성된 바우처를 반환") + void 쿠폰_생성_성공() { + // 1,000원 할인 쿠폰 생성 + int amount = 1_000; + Voucher voucher = createFixedVoucher(1L, amount); + Voucher saved = voucherRepository.save(voucher); + + // 생성된 바우처 반환 + assertThat(saved).isEqualTo(voucher); + } + + @Test + void 전체_쿠폰_목록_조회_성공() { + // 1,000원 할인 쿠폰, 10% 할인 쿠폰 생성 + int amount = 1_000; + Voucher voucher = createFixedVoucher(1L, amount); + voucherRepository.save(voucher); + + int percent = 10; + Voucher voucher2 = createPercentVoucher(2L, percent); + voucherRepository.save(voucher2); + + // 전체 쿠폰 목록 조회 + List vouchers = voucherRepository.findAll(); + + // 저장된 2개의 쿠폰이 조회 + assertThat(vouchers).hasSize(2); + } + + @DisplayName("특정 쿠폰 종류에 해당하는 쿠폰 목록을 조회할 수 있습니다.") + @Test + void findAllByVoucherType() { + // given + Voucher fixedVoucher = createFixedVoucher(1L, 1000); + voucherRepository.save(fixedVoucher); + + Voucher percentVoucher = createPercentVoucher(2L, 10); + voucherRepository.save(percentVoucher); + + // when + List found = voucherRepository.findAllByVoucherType(FIXED); + + // then + assertThat(found).hasSize(1); + } + + @Test + void 쿠폰_아이디로_조회_성공() { + // 1,000원 할인 쿠폰 생성 + int amount = 1_000; + Voucher voucher = createFixedVoucher(1L, amount); + voucherRepository.save(voucher); + + // 쿠폰 번호로 조회 + Voucher found = voucherRepository.findById(voucher.getId()).get(); + + // 저장한 쿠폰과 동일한 쿠폰 반환 + assertThat(found.getId()).isEqualTo(voucher.getId()); + } + + @Test + void 쿠폰_번호로_삭제_성공() { + // 1,000원 할인 쿠폰 생성 + int amount = 1_000; + Voucher voucher = createFixedVoucher(1L, amount); + voucherRepository.save(voucher); + + // 쿠폰 삭제 + voucherRepository.deleteById(voucher.getId()); + + // 쿠폰이 삭제됨 + List vouchers = voucherRepository.findAll(); + assertThat(vouchers).hasSize(0); + } + + @DisplayName("저장된 쿠폰 id 중 최댓값을 구할 수 있다.") + @Test + void findLatestVoucherId() { + // given + Voucher voucher1 = createFixedVoucher(1L, 1000); + Voucher voucher2 = createFixedVoucher(2L, 2000); + Voucher voucher3 = createPercentVoucher(3L, 30); + voucherRepository.save(voucher1); + voucherRepository.save(voucher2); + voucherRepository.save(voucher3); + + // when + Optional latestId = voucherRepository.findLatestVoucherId(); + + // then + assertThat(latestId.isEmpty()).isFalse(); + assertThat(latestId.get()).isEqualTo(3L); + } + + @DisplayName("저장된 쿠폰이 없는 경우 쿠폰 id 중 최댓값을 요청하면 빈 Optional을 반환한다.") + @Test + void findLatestVoucherIdInEmpty() { + // given when + Optional latestId = voucherRepository.findLatestVoucherId(); + + // then + assertThat(latestId.isEmpty()).isTrue(); + } + + private static Voucher createFixedVoucher(Long id, int amount) { + return new Voucher.Builder(id, FIXED, amount).build(); + } + + private static Voucher createPercentVoucher(Long id, int percent) { + return new Voucher.Builder(id, PERCENT, percent).build(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/repository/voucher/JsonFileVoucherRepositoryTest.java b/src/test/java/team/marco/voucher_management_system/repository/voucher/JsonFileVoucherRepositoryTest.java new file mode 100644 index 0000000000..baf3be6ab1 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/repository/voucher/JsonFileVoucherRepositoryTest.java @@ -0,0 +1,163 @@ +package team.marco.voucher_management_system.repository.voucher; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import team.marco.voucher_management_system.domain.voucher.Voucher; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.*; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.PERCENT; + +@SpringBootTest +@ActiveProfiles("test") +class JsonFileVoucherRepositoryTest { + private JsonFileVoucherRepository fileVoucherRepository; + + public JsonFileVoucherRepositoryTest(@Value("${file.path.voucher_data}") String path) { + fileVoucherRepository = new JsonFileVoucherRepository(path); + } + + @DisplayName("바우처를 생성할 수 있다.") + @Test + void save() { + // 1,000원 할인 쿠폰 생성 + int amount = 1_000; + Voucher voucher = createFixedVoucher(1L, amount); + Voucher saved = fileVoucherRepository.save(voucher); + + // 생성된 바우처 반환 + assertThat(saved).isEqualTo(voucher); + } + + @DisplayName("전체 쿠폰 목록을 조회 할 수 있다.") + @Test + void findAll() { + // 1,000원 할인 쿠폰, 10% 할인 쿠폰 생성 + int discountAmount = 1_000; + Voucher voucher = createFixedVoucher(1L, discountAmount); + fileVoucherRepository.save(voucher); + + int percent = 10; + Voucher voucher2 = createPercentVoucher(2L, percent); + fileVoucherRepository.save(voucher2); + + // 전체 쿠폰 목록 조회 + List vouchers = fileVoucherRepository.findAll(); + + // 저장된 2개의 쿠폰이 조회 + assertThat(vouchers).hasSize(2); + } + + @DisplayName("특정 쿠폰 종류에 해당하는 쿠폰 목록을 조회할 수 있습니다.") + @Test + void findAllByVoucherType() { + // given + Voucher fixedVoucher = createFixedVoucher(1L, 1000); + fileVoucherRepository.save(fixedVoucher); + + Voucher percentVoucher = createPercentVoucher(2L, 10); + fileVoucherRepository.save(percentVoucher); + + // when + List found = fileVoucherRepository.findAllByVoucherType(FIXED); + + // then + assertThat(found).hasSize(1); + } + + @DisplayName("쿠폰 id로 쿠폰을 검색할 수 있다.") + @Test + void findById() { + // given + Voucher voucher = createFixedVoucher(1L, 1000); + fileVoucherRepository.save(voucher); + Long voucherId = voucher.getId(); + + // when + Optional found = fileVoucherRepository.findById(voucherId); + + // then + assertThat(found.get()).isNotNull(); + assertThat(found.get()) + .extracting("id", "discountValue") + .containsExactly(1L, 1000); + } + + @DisplayName("존재하지 않는 쿠폰 id로 검색하면 빈 Optional이 반환된다.") + @Test + void findByIdWithInvaildId() { + // given + Long randomId = -1L; + + // when + Optional found = fileVoucherRepository.findById(randomId); + + // then + assertThat(found.isEmpty()).isTrue(); + } + + @DisplayName("쿠폰 id로 쿠폰을 삭제할 수 있다.") + @Test + void deleteById() { + // given + Voucher voucher = createFixedVoucher(1L, 1000); + fileVoucherRepository.save(voucher); + Long voucherId = voucher.getId(); + + Optional before = fileVoucherRepository.findById(voucherId); + assertThatNoException().isThrownBy(before::get); + + // when + fileVoucherRepository.deleteById(voucherId); + + // then + Optional after = fileVoucherRepository.findById(voucherId); + assertThatThrownBy(after::get) + .isInstanceOf(NoSuchElementException.class); + } + + @DisplayName("저장된 쿠폰 id 중 최댓값을 구할 수 있다.") + @Test + void findLatestVoucherId() { + // given + Voucher voucher1 = createFixedVoucher(1L, 1000); + Voucher voucher2 = createFixedVoucher(2L, 2000); + Voucher voucher3 = createPercentVoucher(3L, 30); + fileVoucherRepository.save(voucher1); + fileVoucherRepository.save(voucher2); + fileVoucherRepository.save(voucher3); + + // when + Optional latestId = fileVoucherRepository.findLatestVoucherId(); + + // then + assertThat(latestId.isEmpty()).isFalse(); + assertThat(latestId.get()).isEqualTo(3L); + } + + @DisplayName("저장된 쿠폰이 없는 경우 쿠폰 id 중 최댓값을 요청하면 빈 Optional을 반환한다.") + @Test + void findLatestVoucherIdInEmpty() { + // given when + Optional latestId = fileVoucherRepository.findLatestVoucherId(); + + // then + assertThat(latestId.isEmpty()).isTrue(); + } + + private static Voucher createFixedVoucher(Long id, int amount) { + return new Voucher.Builder(id, FIXED, amount).build(); + } + + private static Voucher createPercentVoucher(Long id, int percent) { + return new Voucher.Builder(id, PERCENT, percent).build(); + } + +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/repository/voucher/MemoryVoucherRepositoryTest.java b/src/test/java/team/marco/voucher_management_system/repository/voucher/MemoryVoucherRepositoryTest.java new file mode 100644 index 0000000000..ba2adb42e9 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/repository/voucher/MemoryVoucherRepositoryTest.java @@ -0,0 +1,160 @@ +package team.marco.voucher_management_system.repository.voucher; + + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import team.marco.voucher_management_system.domain.voucher.Voucher; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.*; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.PERCENT; + +class MemoryVoucherRepositoryTest { + private MemoryVoucherRepository voucherRepository; + + @BeforeEach + void setUp() { + voucherRepository = new MemoryVoucherRepository(); + } + + @DisplayName("바우처를 생성할 수 있다.") + @Test + void save() { + // 1,000원 할인 쿠폰 생성 + int amount = 1_000; + Voucher voucher = createFixedVoucher(1L, amount); + Voucher saved = voucherRepository.save(voucher); + + // 생성된 바우처 반환 + assertThat(saved).isEqualTo(voucher); + } + + @DisplayName("전체 쿠폰 목록을 조회 할 수 있다.") + @Test + void findAll() { + // 1,000원 할인 쿠폰, 10% 할인 쿠폰 생성 + int discountAmount = 1_000; + Voucher voucher = createFixedVoucher(1L, discountAmount); + voucherRepository.save(voucher); + + int percent = 10; + Voucher voucher2 = createPercentVoucher(2L, percent); + voucherRepository.save(voucher2); + + // 전체 쿠폰 목록 조회 + List vouchers = voucherRepository.findAll(); + + // 저장된 2개의 쿠폰이 조회 + assertThat(vouchers).hasSize(2); + } + + @DisplayName("특정 쿠폰 종류에 해당하는 쿠폰 목록을 조회할 수 있습니다.") + @Test + void findAllByVoucherType() { + // given + Voucher fixedVoucher = createFixedVoucher(1L, 1000); + voucherRepository.save(fixedVoucher); + + Voucher percentVoucher = createPercentVoucher(2L, 10); + voucherRepository.save(percentVoucher); + + // when + List found = voucherRepository.findAllByVoucherType(FIXED); + + // then + assertThat(found).hasSize(1); + } + + @DisplayName("쿠폰 id로 쿠폰을 검색할 수 있다.") + @Test + void findById() { + // given + Voucher voucher = createFixedVoucher(1L, 1000); + voucherRepository.save(voucher); + Long voucherId = voucher.getId(); + + // when + Optional found = voucherRepository.findById(voucherId); + + // then + assertThat(found.get()).isNotNull(); + assertThat(found.get()) + .extracting("id", "discountValue") + .containsExactly(1L, 1000); + } + + @DisplayName("존재하지 않는 쿠폰 id로 검색하면 빈 Optional이 반환된다.") + @Test + void findByIdWithInvaildId() { + // given + Long randomId = -1L; + + // when + Optional found = voucherRepository.findById(randomId); + + // then + assertThat(found.isEmpty()).isTrue(); + } + + @DisplayName("쿠폰 id로 쿠폰을 삭제할 수 있다.") + @Test + void deleteById() { + // given + Voucher voucher = createFixedVoucher(1L, 1000); + voucherRepository.save(voucher); + Long voucherId = voucher.getId(); + + Optional before = voucherRepository.findById(voucherId); + assertThatNoException().isThrownBy(before::get); + + // when + voucherRepository.deleteById(voucherId); + + // then + Optional after = voucherRepository.findById(voucherId); + assertThatThrownBy(after::get) + .isInstanceOf(NoSuchElementException.class); + } + + @DisplayName("저장된 쿠폰 id 중 최댓값을 구할 수 있다.") + @Test + void findLatestVoucherId() { + // given + Voucher voucher1 = createFixedVoucher(1L, 1000); + Voucher voucher2 = createFixedVoucher(2L, 2000); + Voucher voucher3 = createPercentVoucher(3L, 30); + voucherRepository.save(voucher1); + voucherRepository.save(voucher2); + voucherRepository.save(voucher3); + + // when + Optional latestId = voucherRepository.findLatestVoucherId(); + + // then + assertThat(latestId.isEmpty()).isFalse(); + assertThat(latestId.get()).isEqualTo(3L); + } + + @DisplayName("저장된 쿠폰이 없는 경우 쿠폰 id 중 최댓값을 요청하면 빈 Optional을 반환한다.") + @Test + void findLatestVoucherIdInEmpty() { + // given when + Optional latestId = voucherRepository.findLatestVoucherId(); + + // then + assertThat(latestId.isEmpty()).isTrue(); + } + + private static Voucher createFixedVoucher(Long id, int amount) { + return new Voucher.Builder(id, FIXED, amount).build(); + } + + private static Voucher createPercentVoucher(Long id, int percent) { + return new Voucher.Builder(id, PERCENT, percent).build(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/service/BlacklistServiceTest.java b/src/test/java/team/marco/voucher_management_system/service/BlacklistServiceTest.java new file mode 100644 index 0000000000..26c5cea163 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/service/BlacklistServiceTest.java @@ -0,0 +1,39 @@ +package team.marco.voucher_management_system.service; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import team.marco.voucher_management_system.controller.customer.dto.CustomerIdAndName; +import team.marco.voucher_management_system.repository.custromer.BlacklistRepository; +import team.marco.voucher_management_system.repository.custromer.CsvBlacklistRepository; +import team.marco.voucher_management_system.service.customer.BlacklistService; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@ActiveProfiles("test") +class BlacklistServiceTest { + private BlacklistService blacklistService; + private BlacklistRepository blacklistRepository; + + public BlacklistServiceTest(@Value("${file.path.blacklist}") String path) { + blacklistRepository = new CsvBlacklistRepository(path); + blacklistService = new BlacklistService(blacklistRepository); + } + + @DisplayName("파일에 저장된 블랙리스트를 조회할 수 있습니다.") + @Test + void test() { + // given - 파일에 미리 2명의 사용자를 추가해 놓았습니다. + + // when + List blacklist = blacklistService.getBlacklist(); + + // then + assertThat(blacklist).hasSize(2); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/service/CustomerServiceTest.java b/src/test/java/team/marco/voucher_management_system/service/CustomerServiceTest.java new file mode 100644 index 0000000000..9aeaa12517 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/service/CustomerServiceTest.java @@ -0,0 +1,71 @@ +package team.marco.voucher_management_system.service; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ActiveProfiles; +import team.marco.voucher_management_system.domain.customer.Customer; +import team.marco.voucher_management_system.repository.custromer.CustomerRepository; +import team.marco.voucher_management_system.service.customer.CustomerService; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@ActiveProfiles("test") +class CustomerServiceTest { + @Autowired + private CustomerService customerService; + + @Autowired + private CustomerRepository customerRepository; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @BeforeEach + void setUp() { + String query = "DELETE FROM customers"; + jdbcTemplate.update(query); + } + + @DisplayName("사용자 ID로 사용자를 조회할 수 있습니다.") + @Test + void findCustomerById() { + // given + Customer customer = createCustomer("test", "test@gmail.com"); + customerRepository.insert(customer); + + // when + Customer found = customerService.findCustomerById(customer.getId()); + + // then + assertThat(found.getId()).isEqualTo(customer.getId()); + assertThat(found.getName()).isEqualTo(customer.getName()); + assertThat(found.getEmail()).isEqualTo(customer.getEmail()); + } + + @DisplayName("사용자를 email로 조회할 수 있다.") + @Test + void findCustomerByEmail() { + // given + String email = "test@gmail.com"; + Customer customer = createCustomer("test", email); + customerRepository.insert(customer); + + // when + Customer found = customerService.findCustomerByEmail(email); + + // then + assertThat(found.getEmail()).isEqualTo(email); + assertThat(found.getName()).isEqualTo(customer.getName()); + } + + private Customer createCustomer(String name, String email) { + return new Customer + .Builder(name, email) + .build(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/service/VoucherServiceTest.java b/src/test/java/team/marco/voucher_management_system/service/VoucherServiceTest.java new file mode 100644 index 0000000000..69f78342d3 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/service/VoucherServiceTest.java @@ -0,0 +1,152 @@ +package team.marco.voucher_management_system.service; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ActiveProfiles; +import team.marco.voucher_management_system.controller.voucher.dto.VoucherCreateRequest; +import team.marco.voucher_management_system.domain.voucher.Voucher; +import team.marco.voucher_management_system.domain.voucher.VoucherType; +import team.marco.voucher_management_system.repository.voucher.VoucherRepository; +import team.marco.voucher_management_system.service.voucher.VoucherCreateServiceRequest; +import team.marco.voucher_management_system.service.voucher.VoucherService; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.FIXED; +import static team.marco.voucher_management_system.domain.voucher.VoucherType.PERCENT; + +@SpringBootTest +@ActiveProfiles("test") +class VoucherServiceTest { + @Autowired + private VoucherService voucherService; + + @Autowired + private VoucherRepository voucherRepository; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @BeforeEach + void setUp() { + String query = "DELETE FROM vouchers"; + jdbcTemplate.update(query); + } + + @DisplayName("고정 할인 쿠폰을 생성할 수 있습니다.") + @Test + void createFixedVoucher() { + // given + int amount = 1000; + VoucherCreateServiceRequest request = new VoucherCreateServiceRequest( + FIXED, + amount); + + // when + Voucher returned = voucherService.createVoucher(request); + + // then + assertThat(returned.getVoucherType()).isEqualTo(FIXED); + assertThat(returned.getDiscountValue()).isEqualTo(amount); + } + + @DisplayName("퍼센트 할인 쿠폰을 생성할 수 있습니다.") + @Test + void createPercentVoucher() { + // given + int percent = 10; + VoucherCreateServiceRequest request = new VoucherCreateServiceRequest( + PERCENT, + percent); + + // when + Voucher returned = voucherService.createVoucher(request); + + // then + assertThat(returned.getVoucherType()).isEqualTo(PERCENT); + assertThat(returned.getDiscountValue()).isEqualTo(percent); + } + + @DisplayName("전체 쿠폰 목록을 조회할 수 있습니다.") + @Test + void getVouchers() { + // given + Voucher voucher = createFixedVoucher(1L, 1000); + Voucher voucher2 = createPercentVoucher(2L,10); + voucherRepository.save(voucher); + voucherRepository.save(voucher2); + + // when + List returned = voucherService.getVouchers(); + + // then + assertThat(returned).hasSize(2); + } + + @DisplayName("특정 쿠폰 유형에 해당하는 쿠폰 목록을 조회할 수 있습니다.") + @Test + void getVouchersByVoucherType() { + // given + VoucherType voucherType = FIXED; + Voucher fixedVoucher = createFixedVoucher(1L, 1000); + Voucher percentVoucher = createPercentVoucher(2L, 10); + voucherRepository.save(fixedVoucher); + voucherRepository.save(percentVoucher); + + // when + List found = voucherService.getVouchersByVoucherType(voucherType); + + // then + assertThat(found).hasSize(1); + } + + @DisplayName("쿠폰 아이디로 쿠폰을 조회할 수 있습니다.") + @Test + void getVoucher() { + // given + Voucher voucher = createFixedVoucher(1L, 1000); + voucherRepository.save(voucher); + + // when + Voucher found = voucherService.getVoucher(voucher.getId()); + + // then + assertThat(found.getId()).isEqualTo(voucher.getId()); + } + + @DisplayName("쿠폰 아이디로 쿠폰을 삭제할 수 있습니다.") + @Test + void deleteVoucher() { + // given + Voucher voucher = createFixedVoucher(1L, 1000); + voucherRepository.save(voucher); + + // when + voucherService.deleteVoucher(voucher.getId()); + + // then + List vouchers = voucherRepository.findAll(); + assertThat(vouchers).hasSize(0); + } + + private static VoucherCreateRequest createFixedVoucherRequest(int amount) { + return new VoucherCreateRequest(FIXED, amount); + } + + private static VoucherCreateRequest createPercentVoucherRequest(int percent) { + return new VoucherCreateRequest(PERCENT, percent); + } + + private static Voucher createFixedVoucher(Long id, int amount) { + return new Voucher.Builder(id, FIXED, amount).build(); + } + + private static Voucher createPercentVoucher(Long id, int percent) { + return new Voucher.Builder(id, PERCENT, percent).build(); + } +} \ No newline at end of file diff --git a/src/test/java/team/marco/voucher_management_system/util/UUIDUtilTest.java b/src/test/java/team/marco/voucher_management_system/util/UUIDUtilTest.java new file mode 100644 index 0000000000..efe2f0eed0 --- /dev/null +++ b/src/test/java/team/marco/voucher_management_system/util/UUIDUtilTest.java @@ -0,0 +1,60 @@ +package team.marco.voucher_management_system.util; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +class UUIDUtilTest { + + @DisplayName("바이트 배열을 UUID로 변환할 수 있다.") + @Test + void bytesToUUID() { + // given + UUID uuid = UUID.randomUUID(); + byte[] uuidBytes = toBytes(uuid); + + // when + UUID converted = UUIDUtil.bytesToUUID(uuidBytes); + + // then + assertThat(converted).isEqualTo(uuid); + } + + @DisplayName("문자열을 UUID로 변환할 수 있다.") + @Test + void stringToUUID() { + // given + UUID uuid = UUID.randomUUID(); + String uuidString = uuid.toString(); + + // when + UUID converted = UUIDUtil.stringToUUID(uuidString); + + // then + assertThat(converted).isEqualTo(uuid); + } + + @DisplayName("UUID를 바이트 배열로 변환할 수 있다.") + @Test + void uuidToBytes() { + // given + UUID uuid = UUID.randomUUID(); + + // when + byte[] converted = UUIDUtil.uuidToBytes(uuid); + + // then + assertThat(converted).isEqualTo(toBytes(uuid)); + } + + private byte[] toBytes(UUID uuid) { + ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(uuid.getMostSignificantBits()); + byteBuffer.putLong(uuid.getLeastSignificantBits()); + return byteBuffer.array(); + } +} \ No newline at end of file diff --git a/src/test/resources/test_blacklist.csv b/src/test/resources/test_blacklist.csv new file mode 100644 index 0000000000..3f6a9afedd --- /dev/null +++ b/src/test/resources/test_blacklist.csv @@ -0,0 +1,3 @@ +id,name +461b8847-578d-43c7-8472-d9374bbac41a,정의진 +461b8847-578d-43c7-8472-d9374bbac42b,김현우 diff --git a/src/test/resources/test_voucher_data.json b/src/test/resources/test_voucher_data.json new file mode 100644 index 0000000000..0637a088a0 --- /dev/null +++ b/src/test/resources/test_voucher_data.json @@ -0,0 +1 @@ +[] \ No newline at end of file