diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..c2065bc262 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..bfd93208fe --- /dev/null +++ b/build.gradle @@ -0,0 +1,36 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'org.programmers' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter' + implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-aop' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'com.mysql:mysql-connector-j:8.0.32' + implementation 'org.projectlombok:lombok' + implementation 'org.mapstruct:mapstruct:1.4.2.Final' + annotationProcessor 'org.projectlombok:lombok' + annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final' + annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' + testImplementation 'org.assertj:assertj-core:3.24.2' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +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/settings.gradle b/settings.gradle new file mode 100644 index 0000000000..0fb15a766c --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'springboot.basic' diff --git a/src/main/java/org/programmers/springboot/basic/AppConstants.java b/src/main/java/org/programmers/springboot/basic/AppConstants.java new file mode 100644 index 0000000000..9e4ac8a466 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/AppConstants.java @@ -0,0 +1,16 @@ +package org.programmers.springboot.basic; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class AppConstants { + + public static final Long MIN_FIXED_DISCOUNT = 0L; + public static final Long MIN_PERCENT_DISCOUNT = 0L; + public static final Long MAX_PERCENT_DISCOUNT = 100L; + public static final int NONE = 0; + public static final int FIXED_AMOUNT = 1; + public static final int PERCENT_DISCOUNT = 2; + public static final String SUCCESS = "Complete success!"; +} diff --git a/src/main/java/org/programmers/springboot/basic/VoucherManagementApplication.java b/src/main/java/org/programmers/springboot/basic/VoucherManagementApplication.java new file mode 100644 index 0000000000..1455b047b4 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/VoucherManagementApplication.java @@ -0,0 +1,36 @@ +package org.programmers.springboot.basic; + +import lombok.RequiredArgsConstructor; +import org.programmers.springboot.basic.util.manager.CommandManager; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.servlet.server.ServletWebServerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Profile; + +@SpringBootApplication +@RequiredArgsConstructor +public class VoucherManagementApplication { + + private final ApplicationContext applicationContext; + + public static void main(String[] args) { + SpringApplication.run(VoucherManagementApplication.class, args); + } + + @Profile(value = "web") + @Bean + public ServletWebServerFactory tomcatServetContainer() { + return new TomcatServletWebServerFactory(); + } + + @Profile(value = "command") + @Bean + public void init() { + CommandManager commandManager = applicationContext.getBean(CommandManager.class); + commandManager.run(); + System.exit(SpringApplication.exit(applicationContext, () -> 0)); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/aop/LoggerAspect.java b/src/main/java/org/programmers/springboot/basic/aop/LoggerAspect.java new file mode 100644 index 0000000000..f3a14e6176 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/aop/LoggerAspect.java @@ -0,0 +1,56 @@ +package org.programmers.springboot.basic.aop; + +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.*; +import org.springframework.stereotype.Component; + +@Slf4j +@Aspect +@Component +public class LoggerAspect { + + private static void logMethodCall(JoinPoint joinPoint) { + log.warn("'{}' method called in '{}'", + joinPoint.getSignature().getName(), + joinPoint.getSignature().getDeclaringTypeName()); + } + + @Pointcut("execution(void org.programmers.springboot.basic..*Controller.*(..)) || " + + "execution(void org.programmers.springboot.basic..*Repository.*(..)) || " + + "execution(void org.programmers.springboot.basic..*Mapper.*(..)) || " + + "execution(void org.programmers.springboot.basic..*Service.*(..))") + public void voidMethods() {} + + @Pointcut("execution(* org.programmers.springboot.basic..*Controller.*(..)) && !voidMethods() ||" + + "execution(* org.programmers.springboot.basic..*Repository.*(..)) && ! voidMethods() || " + + "execution(* org.programmers.springboot.basic..*Service.*(..)) && ! voidMethods() || " + + "execution(* org.programmers.springboot.basic..*Mapper.*(..)) && ! voidMethods()") + public void nonVoidMethods() {} + + @Pointcut("execution(* org.programmers.springboot.basic..*.*(..))") + public void allMethods() {} + + @Before("voidMethods()") + public void logBefore(JoinPoint joinPoint) { + logMethodCall(joinPoint); + } + + @Around("nonVoidMethods()") + public Object logAroundWithResult(ProceedingJoinPoint joinPoint) throws Throwable { + log.info("'{}' method called in {}", + joinPoint.getSignature().getName(), + joinPoint.getSignature().getDeclaringTypeName()); + Object result = joinPoint.proceed(); + log.info("After '{}' method called with result '{}'", + joinPoint.getSignature().getName(), + result != null ? result.toString() : "null"); + return result; + } + + @AfterThrowing(pointcut = "allMethods()", throwing = "runtimeException") + public void logException(RuntimeException runtimeException) { + log.warn(runtimeException.getMessage()); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/config/AppConfig.java b/src/main/java/org/programmers/springboot/basic/config/AppConfig.java new file mode 100644 index 0000000000..12e55e6b5f --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/config/AppConfig.java @@ -0,0 +1,18 @@ +package org.programmers.springboot.basic.config; + + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.filter.HiddenHttpMethodFilter; + +@Profile("default") +@Configuration +public class AppConfig { + + @Bean + public HiddenHttpMethodFilter hiddenHttpMethodFilter() { + return new HiddenHttpMethodFilter(); + } +} + diff --git a/src/main/java/org/programmers/springboot/basic/config/VoucherConfig.java b/src/main/java/org/programmers/springboot/basic/config/VoucherConfig.java new file mode 100644 index 0000000000..2a73431196 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/config/VoucherConfig.java @@ -0,0 +1,33 @@ +package org.programmers.springboot.basic.config; + +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; +import org.programmers.springboot.basic.domain.voucher.service.validate.FixedAmountVoucherValidationStrategy; +import org.programmers.springboot.basic.domain.voucher.service.validate.PercentDiscountVoucherValidationStrategy; +import org.programmers.springboot.basic.domain.voucher.service.validate.VoucherValidationStrategy; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.HashMap; +import java.util.Map; + +@Configuration +public class VoucherConfig { + + @Bean + public FixedAmountVoucherValidationStrategy fixedAmountVoucherValidator() { + return new FixedAmountVoucherValidationStrategy(); + } + + @Bean + public PercentDiscountVoucherValidationStrategy percentDiscountVoucherValidator() { + return new PercentDiscountVoucherValidationStrategy(); + } + + @Bean + public Map validationStrategyMap() { + Map handler = new HashMap<>(); + handler.put(VoucherType.FIXED, fixedAmountVoucherValidator()); + handler.put(VoucherType.PERCENT, percentDiscountVoucherValidator()); + return handler; + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/controller/CustomerController.java b/src/main/java/org/programmers/springboot/basic/domain/customer/controller/CustomerController.java new file mode 100644 index 0000000000..b4ba9997b8 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/controller/CustomerController.java @@ -0,0 +1,118 @@ +package org.programmers.springboot.basic.domain.customer.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.dto.CustomerRequestDto; +import org.programmers.springboot.basic.domain.customer.dto.CustomerResponseDto; +import org.programmers.springboot.basic.domain.customer.exception.*; +import org.programmers.springboot.basic.domain.customer.mapper.CustomerMapper; +import org.programmers.springboot.basic.domain.customer.service.CustomerService; +import org.programmers.springboot.basic.util.manager.ConsoleIOManager; +import org.springframework.stereotype.Controller; + +import java.util.List; + +@Slf4j +@Controller +@RequiredArgsConstructor +public class CustomerController { + + private final ConsoleIOManager consoleIOManager; + private final CustomerService customerService; + public void create() { + + String name = null; + String email = null; + + consoleIOManager.printCustomerCreateHandler(); + + try { + name = consoleIOManager.getInput(); + email = consoleIOManager.getInput(); + CustomerRequestDto requestDto = CustomerMapper.INSTANCE.mapToRequestDto(name, email); + customerService.create(requestDto); + } catch (IllegalEmailException e) { + log.warn("Your input is Invalid Email Type: '{}'", email); + } catch (DuplicateEmailException e) { + log.warn("Duplicate email '{}' is already exists", email); + } + } + + public void list() { + + List responseDtos = customerService.findAllCustomer(); + responseDtos.forEach(CustomerResponseDto::printCustomerInfo); + } + + public void blacklist() { + + List responseDtos = customerService.findByCustomerIsBlack(); + responseDtos.forEach(CustomerResponseDto::printCustomerInfo); + } + + public void addToBlackList() { + + String input = null; + + consoleIOManager.printAddBlackHandler(); + + try { + input = consoleIOManager.getInput(); + CustomerRequestDto requestDto = CustomerMapper.INSTANCE.mapToRequestDtoWithUUID(input); + customerService.addBlackCustomer(requestDto); + } catch (IllegalArgumentException e) { + log.warn("Your input is Invalid UUID string: {}", input); + } catch (DuplicateBlackCustomerException e) { + log.warn("customer of customerId '{}' is already exists from blacklist", input); + } catch (CustomerNotFoundException e) { + log.warn("No customer of customerId '{}' found", input); + } + } + + public void deleteFromBlackList() { + + String input = null; + + consoleIOManager.printDeleteBlackHandler(); + + try { + input = consoleIOManager.getInput(); + CustomerRequestDto requestDto = CustomerMapper.INSTANCE.mapToRequestDtoWithUUID(input); + customerService.deleteBlackCustomer(requestDto); + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", input); + } catch (BlackCustomerNotFoundException e) { + log.warn("No customer found from blacklist that matches the customerId '{}'", input); + } catch (CustomerNotFoundException e) { + log.warn("No customer of customerId '{}' found", input); + } + } + + public void delete() { + + String input = null; + + consoleIOManager.printCustomerDeleteHandler(); + + try { + input = consoleIOManager.getInput(); + CustomerRequestDto requestDto = CustomerMapper.INSTANCE.mapToRequestDtoWithUUID(input); + customerService.deleteCustomer(requestDto); + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", input); + } catch (CustomerNotFoundException e) { + log.warn("No customer of customerId '{}' found", input); + } + } + + public void deleteAll() { + + consoleIOManager.printDeleteAllHandler(); + + String input = consoleIOManager.getInput(); + switch (input) { + case "Y", "y" -> customerService.deleteAll(); + default -> {} + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/dto/CustomerRequestDto.java b/src/main/java/org/programmers/springboot/basic/domain/customer/dto/CustomerRequestDto.java new file mode 100644 index 0000000000..cac8265fff --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/dto/CustomerRequestDto.java @@ -0,0 +1,33 @@ +package org.programmers.springboot.basic.domain.customer.dto; + +import lombok.Builder; +import lombok.Getter; +import org.programmers.springboot.basic.domain.customer.entity.CustomerType; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; + +import java.util.UUID; + +@Builder +@Getter +public class CustomerRequestDto { + + private final UUID customerId; + private final String name; + private final Email email; + private final CustomerType customerType; + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/dto/CustomerResponseDto.java b/src/main/java/org/programmers/springboot/basic/domain/customer/dto/CustomerResponseDto.java new file mode 100644 index 0000000000..cc244143c2 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/dto/CustomerResponseDto.java @@ -0,0 +1,43 @@ +package org.programmers.springboot.basic.domain.customer.dto; + +import lombok.Builder; +import lombok.Getter; +import org.programmers.springboot.basic.domain.customer.entity.CustomerType; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; + +import java.util.UUID; + +@Builder +@Getter +public class CustomerResponseDto { + + private final UUID customerId; + private final String name; + private final Email email; + private final CustomerType customerType; + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } + + public String printCustomerInfo() { + return String.format(""" + customerId: %s + email: %s + name: %s + customerType: %s + --------------------------------- + """, customerId.toString(), email, name, customerType); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/entity/Customer.java b/src/main/java/org/programmers/springboot/basic/domain/customer/entity/Customer.java new file mode 100644 index 0000000000..c0c88d076d --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/entity/Customer.java @@ -0,0 +1,45 @@ +package org.programmers.springboot.basic.domain.customer.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.domain.customer.exception.BlackCustomerNotFoundException; +import org.programmers.springboot.basic.domain.customer.exception.DuplicateBlackCustomerException; + +import java.util.UUID; + +@Slf4j +@Getter +@AllArgsConstructor +public class Customer { + + private final UUID customerId; + private final String name; + private final Email email; + private CustomerType customerType; + + public int getCustomerTypeValue() { + return this.customerType.getValue(); + } + + public boolean equalType(CustomerType type) { + return this.customerType.equals(type); + } + + public void setBlack() { + if (this.equalType(CustomerType.BLACK)) { + log.warn("customer of customerId {} is already exists from blacklist", this.customerId); + throw new DuplicateBlackCustomerException(); + } + this.customerType = CustomerType.BLACK; + } + + public void setNormal() { + if (this.equalType(CustomerType.NORMAL)) { + log.warn("customer of customerId {} is not exists from blacklist", this.customerId); + throw new BlackCustomerNotFoundException(); + } + this.customerType = CustomerType.NORMAL; + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/entity/CustomerType.java b/src/main/java/org/programmers/springboot/basic/domain/customer/entity/CustomerType.java new file mode 100644 index 0000000000..de52db16bd --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/entity/CustomerType.java @@ -0,0 +1,29 @@ +package org.programmers.springboot.basic.domain.customer.entity; + +import org.programmers.springboot.basic.domain.customer.exception.CustomerNotFoundException; + +import java.util.Arrays; + +public enum CustomerType { + + NORMAL(0), + BLACK(1); + + private final int value; + + CustomerType(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public static CustomerType valueOf(int value) { + + return Arrays.stream(values()) + .filter(customer -> customer.getValue() == value) + .findAny() + .orElseThrow(CustomerNotFoundException::new); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/entity/vo/Email.java b/src/main/java/org/programmers/springboot/basic/domain/customer/entity/vo/Email.java new file mode 100644 index 0000000000..d70d79d1ed --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/entity/vo/Email.java @@ -0,0 +1,27 @@ +package org.programmers.springboot.basic.domain.customer.entity.vo; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.programmers.springboot.basic.domain.customer.exception.IllegalEmailException; + +import java.util.regex.Pattern; + +@Getter +@RequiredArgsConstructor +public class Email { + + private static final String REGEX = "^[_a-z0-9-]+(.[_a-z0-9-]+)*@(?:\\w+\\.)+\\w+$"; + private static final Pattern pattern = Pattern.compile(REGEX); + + private final String email; + + public static Email valueOf(String email) { + return new Email(email); + } + + public void validate() { + if (!pattern.matcher(email).matches()) { + throw new IllegalEmailException(); + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/exception/BlackCustomerNotFoundException.java b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/BlackCustomerNotFoundException.java new file mode 100644 index 0000000000..fa38991824 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/BlackCustomerNotFoundException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.customer.exception; + +public class BlackCustomerNotFoundException extends RuntimeException { + + public BlackCustomerNotFoundException() { + super("No matching BLACK customers found!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/exception/CustomerNotFoundException.java b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/CustomerNotFoundException.java new file mode 100644 index 0000000000..bf054b4941 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/CustomerNotFoundException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.customer.exception; + +public class CustomerNotFoundException extends RuntimeException { + + public CustomerNotFoundException() { + super("No matching customers found!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/exception/DuplicateBlackCustomerException.java b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/DuplicateBlackCustomerException.java new file mode 100644 index 0000000000..d6ac7bb443 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/DuplicateBlackCustomerException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.customer.exception; + +public class DuplicateBlackCustomerException extends RuntimeException { + + public DuplicateBlackCustomerException() { + super("Duplicate customer already exists in blacklist!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/exception/DuplicateEmailException.java b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/DuplicateEmailException.java new file mode 100644 index 0000000000..8c9c85fdab --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/DuplicateEmailException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.customer.exception; + +public class DuplicateEmailException extends RuntimeException { + + public DuplicateEmailException() { + super("Duplicate Email already exists!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/exception/IllegalEmailException.java b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/IllegalEmailException.java new file mode 100644 index 0000000000..b8c16312f3 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/exception/IllegalEmailException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.customer.exception; + +public class IllegalEmailException extends RuntimeException { + + public IllegalEmailException() { + super("Illegal Email Type!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/mapper/CustomerMapper.java b/src/main/java/org/programmers/springboot/basic/domain/customer/mapper/CustomerMapper.java new file mode 100644 index 0000000000..f6bf3b117c --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/mapper/CustomerMapper.java @@ -0,0 +1,51 @@ +package org.programmers.springboot.basic.domain.customer.mapper; + +import org.mapstruct.Context; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.ReportingPolicy; +import org.mapstruct.factory.Mappers; +import org.programmers.springboot.basic.domain.customer.dto.CustomerRequestDto; +import org.programmers.springboot.basic.domain.customer.dto.CustomerResponseDto; +import org.programmers.springboot.basic.domain.customer.entity.Customer; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.util.generator.UUIDGenerator; + +import java.util.UUID; + +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface CustomerMapper { + + CustomerMapper INSTANCE = Mappers.getMapper(CustomerMapper.class); + + @Mapping(target = "name", source = "name") + @Mapping(target = "email", expression = "java(mapToEmail(email))") + @Mapping(target = "customerType", constant = "NORMAL") + CustomerRequestDto mapToRequestDto(String name, String email); + + @Mapping(target = "customerId", source = "customerId") + CustomerRequestDto mapToRequestDtoWithUUID(String customerId); + + CustomerResponseDto mapToResponseDto(Customer customer); + + @Mapping(target = "customerId", expression = "java(generateUUID(uuidGenerator))") + Customer mapTopEntityWithGenerator(CustomerRequestDto customerRequestDto, @Context UUIDGenerator uuidGenerator); + + @Mapping(target = "customerId", expression = "java(generateUUID(uuidGenerator))") + @Mapping(target = "name", source = "name") + @Mapping(target = "email", source = "email") + @Mapping(target = "customerType", constant = "NORMAL") + Customer mapToEntityAllArgsWithGenerator(CustomerRequestDto customerRequestDto, @Context UUIDGenerator uuidGenerator); + + default UUID mapToUUID(String value) { + return UUID.fromString(value); + } + + default UUID generateUUID(@Context UUIDGenerator uuidGenerator) { + return uuidGenerator.generateUUID(); + } + + default Email mapToEmail(String email) { + return Email.valueOf(email); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/repository/CustomerRepository.java b/src/main/java/org/programmers/springboot/basic/domain/customer/repository/CustomerRepository.java new file mode 100644 index 0000000000..41a4597e95 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/repository/CustomerRepository.java @@ -0,0 +1,20 @@ +package org.programmers.springboot.basic.domain.customer.repository; + +import org.programmers.springboot.basic.domain.customer.entity.Customer; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface CustomerRepository { + + void save(Customer customer); + Optional findByEmail(Email email); + Optional findById(UUID customerId); + List findAll(); + List findBlack(); + void update(Customer customer); + void delete(Customer customer); + void deleteAll(); +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/repository/JdbcCustomerRepository.java b/src/main/java/org/programmers/springboot/basic/domain/customer/repository/JdbcCustomerRepository.java new file mode 100644 index 0000000000..e2753a2941 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/repository/JdbcCustomerRepository.java @@ -0,0 +1,107 @@ +package org.programmers.springboot.basic.domain.customer.repository; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.entity.Customer; +import org.programmers.springboot.basic.domain.customer.entity.CustomerType; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.util.converter.UUIDConverter; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Slf4j +@Repository +@RequiredArgsConstructor +public class JdbcCustomerRepository implements CustomerRepository { + + private final JdbcTemplate jdbcTemplate; + + private RowMapper customerRowMapper() { + return (rs, rowNum) -> { + UUID customerId = UUIDConverter.toUUID(rs.getBytes("customer_id")); + String name = rs.getString("name"); + Email email = Email.valueOf(rs.getString("email")); + CustomerType customerType = CustomerType.valueOf(rs.getInt("isBlack")); + return new Customer(customerId, name, email, customerType); + }; + } + + @Override + public void save(final Customer customer) { + String sql = "INSERT INTO customers (customer_id, name, email, isBlack) " + + "VALUES(UUID_TO_BIN(?), ?, ?, ?)"; + jdbcTemplate.update(sql, + customer.getCustomerId().toString().getBytes(), + customer.getName(), customer.getEmail(), + customer.getCustomerTypeValue()); + } + + @Override + public Optional findByEmail(Email email) { + String sql = "SELECT * FROM customers WHERE email = ?"; + try { + return Optional.ofNullable(jdbcTemplate.queryForObject(sql, customerRowMapper(), + email.getEmail())); + } catch (EmptyResultDataAccessException e) { + log.warn("No customer found for email: {}", email.getEmail()); + } catch (DataAccessException e) { + log.error("Data access exception: {}", e.toString()); + } + return Optional.empty(); + } + + @Override + public Optional findById(UUID customerId) { + String sql = "SELECT * FROM customers WHERE customer_id = UUID_TO_BIN(?)"; + try { + return Optional.ofNullable(jdbcTemplate.queryForObject(sql, customerRowMapper(), + (Object) UUIDConverter.toBytes(customerId))); + } catch (EmptyResultDataAccessException e) { + log.warn("No customer found for customerId: {}", customerId); + } catch (DataAccessException e) { + log.error("Data access Exception: {}", e.toString()); + } + return Optional.empty(); + } + + @Override + public List findAll() { + String sql = "SELECT * FROM customers ORDER BY customer_id"; + return jdbcTemplate.query(sql, customerRowMapper()); + } + + @Override + public List findBlack() { + String sql = "SELECT * FROM customers WHERE isBlack = TRUE"; + return jdbcTemplate.query(sql, customerRowMapper()); + } + + @Override + public void update(Customer customer) { + String sql = "UPDATE customers SET name = ?, email = ?, isBlack = ? " + + "WHERE customer_id = UUID_TO_BIN(?)"; + jdbcTemplate.update(sql, customer.getName(), + customer.getEmail(), + customer.getCustomerTypeValue(), + UUIDConverter.toBytes(customer.getCustomerId())); + } + + @Override + public void delete(Customer customer) { + String sql = "DELETE FROM customers WHERE customer_id = UUID_TO_BIN(?)"; + jdbcTemplate.update(sql, (Object) UUIDConverter.toBytes(customer.getCustomerId())); + } + + @Override + public void deleteAll() { + String sql = "DELETE FROM customers"; + jdbcTemplate.update(sql); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/customer/service/CustomerService.java b/src/main/java/org/programmers/springboot/basic/domain/customer/service/CustomerService.java new file mode 100644 index 0000000000..c17a0dbc34 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/customer/service/CustomerService.java @@ -0,0 +1,125 @@ +package org.programmers.springboot.basic.domain.customer.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.dto.CustomerRequestDto; +import org.programmers.springboot.basic.domain.customer.dto.CustomerResponseDto; +import org.programmers.springboot.basic.domain.customer.entity.Customer; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.domain.customer.exception.*; +import org.programmers.springboot.basic.domain.customer.mapper.CustomerMapper; +import org.programmers.springboot.basic.domain.customer.repository.CustomerRepository; +import org.programmers.springboot.basic.util.generator.UUIDGenerator; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.UUID; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomerService { + + private final CustomerRepository customerRepository; + private final UUIDGenerator uuidGenerator; + + @Transactional + public void create(CustomerRequestDto customerRequestDto) { + + Email email = customerRequestDto.getEmail(); + + email.validate(); + Customer customer = CustomerMapper.INSTANCE.mapToEntityAllArgsWithGenerator(customerRequestDto, uuidGenerator); + + if (isDuplicate(customer)) { + log.warn("Duplicate email {} is already exists", email); + throw new DuplicateEmailException(); + } else { + customerRepository.save(customer); + } + } + + private boolean isDuplicate(Customer customer) { + return customerRepository.findByEmail(customer.getEmail()).isPresent(); + } + + public List findAllCustomer() { + + List customers = findAll(); + return customers.stream() + .map(CustomerMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + public List findByCustomerIsBlack() { + + List customers = findBlackCustomer(); + return customers.stream() + .map(CustomerMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + @Transactional + public void addBlackCustomer(CustomerRequestDto customerRequestDto) { + + UUID customerId = customerRequestDto.getCustomerId(); + + Customer customer = findById(customerId); + customer.setBlack(); + customerRepository.update(customer); + } + + @Transactional + public void deleteCustomer(CustomerRequestDto customerRequestDto) { + + UUID customerId = customerRequestDto.getCustomerId(); + + Customer customer = findById(customerId); + customerRepository.delete(customer); + } + + @Transactional + public void deleteBlackCustomer(CustomerRequestDto customerRequestDto) { + + UUID customerId = customerRequestDto.getCustomerId(); + + Customer customer = findById(customerId); + customer.setNormal(); + customerRepository.update(customer); + } + + public Customer findById(UUID customerId) { + + return customerRepository.findById(customerId) + .orElseThrow(() -> { + log.warn("No customer found for customerId: {}", customerId); + return new CustomerNotFoundException(); + }); + } + + public CustomerResponseDto findByEmail(Email email) { + + email.validate(); + Customer customer = customerRepository.findByEmail(email) + .orElseThrow(() -> { + log.warn("No customer found for email: {}", email); + return new CustomerNotFoundException(); + }); + return CustomerMapper.INSTANCE.mapToResponseDto(customer); + } + + + public List findAll() { + return customerRepository.findAll(); + } + + public List findBlackCustomer() { + return customerRepository.findBlack(); + } + + @Transactional + public void deleteAll() { + customerRepository.deleteAll(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherAPIController.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherAPIController.java new file mode 100644 index 0000000000..665220abd9 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherAPIController.java @@ -0,0 +1,82 @@ +package org.programmers.springboot.basic.domain.voucher.controller; + +import lombok.RequiredArgsConstructor; +import org.programmers.springboot.basic.AppConstants; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherControllerRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; +import org.programmers.springboot.basic.domain.voucher.mapper.VoucherMapper; +import org.programmers.springboot.basic.domain.voucher.service.VoucherService; +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Profile("default") +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/voucher") +public class VoucherAPIController { + + private final VoucherService voucherService; + + @PostMapping("/create") + @ResponseStatus(HttpStatus.CREATED) + public ResponseEntity create(@RequestBody VoucherControllerRequestDto requestDto) { + VoucherType voucherType = VoucherType.valueOf(requestDto.getVoucherType()); + Long discount = Long.parseLong(requestDto.getDiscount()); + + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE.mapToRequestDto(voucherType, discount); + voucherService.create(voucherRequestDto); + return ResponseEntity.ok(AppConstants.SUCCESS); + } + + @GetMapping("/{voucherId}") + @ResponseStatus(HttpStatus.OK) + public ResponseEntity findVoucherById(@PathVariable String voucherId) { + VoucherRequestDto requestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(voucherId); + VoucherResponseDto responseDto = voucherService.findById(requestDto); + return ResponseEntity.ok(responseDto); + } + + @GetMapping() + @ResponseStatus(HttpStatus.OK) + public ResponseEntity> findVoucher( + @RequestParam(name = "voucherId", required = false) String voucherId, + @RequestParam(name = "createdAt", required = false) String createdAt, + @RequestParam(name = "discount", required = false) String discount, + @RequestParam(name = "voucherType", required = false) String voucherType + ) { + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithAllArgs( + voucherId, voucherType, discount, createdAt + ); + List voucherResponseDtos = voucherService.findByOption(voucherRequestDto); + return ResponseEntity.ok(voucherResponseDtos); + } + + @GetMapping("/vouchers") + @ResponseStatus(HttpStatus.OK) + public ResponseEntity> findAllVoucher() { + List vouchers = voucherService.findAll(); + return ResponseEntity.ok(vouchers); + } + + @PatchMapping("/{discount}") + public ResponseEntity updateVoucher(@PathVariable Long discount, + @RequestBody VoucherControllerRequestDto requestDto) { + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE + .mapToRequestDtoWithIdNDiscount(requestDto.getVoucherId(), discount); + voucherService.updateVoucher(voucherRequestDto); + return ResponseEntity.ok(AppConstants.SUCCESS); + } + + @DeleteMapping("/{voucherId}") + public ResponseEntity deleteVoucher(@PathVariable String voucherId) { + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(voucherId); + voucherService.deleteVoucher(voucherRequestDto); + return ResponseEntity.ok(AppConstants.SUCCESS); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherController.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherController.java new file mode 100644 index 0000000000..adaa0b4842 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherController.java @@ -0,0 +1,161 @@ +package org.programmers.springboot.basic.domain.voucher.controller; + +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.AppConstants; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; +import org.programmers.springboot.basic.domain.voucher.exception.DuplicateVoucherException; +import org.programmers.springboot.basic.domain.voucher.exception.IllegalDiscountException; +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; +import org.programmers.springboot.basic.domain.voucher.mapper.VoucherMapper; +import org.programmers.springboot.basic.domain.voucher.service.VoucherService; +import org.programmers.springboot.basic.util.manager.ConsoleIOManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; + +import java.util.List; + +@Slf4j +@Controller +public class VoucherController { + + private final ConsoleIOManager consoleIOManager; + private final VoucherService voucherService; + + @Autowired + public VoucherController(ConsoleIOManager consoleIOManager, VoucherService voucherService) { + this.consoleIOManager = consoleIOManager; + this.voucherService = voucherService; + } + + public void create() { + + boolean flag = true; + int type = AppConstants.NONE; + Long discount = null; + VoucherType voucherType = null; + + while (flag) { + + consoleIOManager.printVoucherCreateHandler(); + + try { + type = consoleIOManager.getInteger(); + } catch (NumberFormatException e) { + log.error(e.toString()); + } + + switch (type) { + case AppConstants.FIXED_AMOUNT, AppConstants.PERCENT_DISCOUNT -> { + discount = requestDiscount(); + flag = false; + } + default -> System.out.println("[System] 잘못된 모드의 접근입니다."); + } + } + + try { + voucherType = VoucherType.valueOf(type); + VoucherRequestDto requestDto = VoucherMapper.INSTANCE.mapToRequestDto(voucherType, discount); + voucherService.create(requestDto); + } catch (IllegalDiscountException e) { + log.error("your input is Invalid Discount Range '{}'", discount); + } catch (DuplicateVoucherException e) { + log.warn("voucher of voucherType '{}' and discount '{} is already exists", voucherType, discount); + } + } + + private Long requestDiscount() { + + boolean flag = true; + String input = null; + Long discount = null; + + while (flag) { + try { + consoleIOManager.printRequestDiscount(); + input = consoleIOManager.getInput(); + discount = Long.parseLong(input); + flag = false; + } catch (NumberFormatException e) { + log.error("Your input is Invalid Type of Long: '{}", input); + } + } + + return discount; + } + + public void list() { + + List responseDtos = voucherService.findAll(); + consoleIOManager.printVoucher(responseDtos); + } + + public void find() { + + consoleIOManager.printFindHandler(); + + String input = consoleIOManager.getInput(); + + try { + VoucherRequestDto requestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(input); + VoucherResponseDto responseDto = this.voucherService.findById(requestDto); + consoleIOManager.printFoundVoucher(responseDto); + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", input); + } catch (VoucherNotFoundException e) { + log.warn("No voucher found for voucherId: '{}'", input); + } + } + + public void update() { + + String input = null; + Long discount = null; + + consoleIOManager.printUpdateHandler(); + + try { + input = consoleIOManager.getInput(); + discount = Long.parseLong(input); + input = consoleIOManager.getInput(); + VoucherRequestDto requestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithIdNDiscount(input, discount); + voucherService.updateVoucher(requestDto); + } catch (NumberFormatException e) { + log.error("Your input is Invalid Type of Long: '{}'", input); + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", input); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", input); + } + } + + public void delete() { + + String input = null; + + consoleIOManager.printVoucherDeleteHandler(); + + try { + input = consoleIOManager.getInput(); + VoucherRequestDto requestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(input); + voucherService.deleteVoucher(requestDto); + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", input); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", input); + } + + } + + public void deleteAll() { + + consoleIOManager.printDeleteAllHandler(); + + switch (consoleIOManager.getInput()) { + case "Y", "y" -> voucherService.deleteAll(); + default -> {} + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherWebController.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherWebController.java new file mode 100644 index 0000000000..fe8642b552 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/controller/VoucherWebController.java @@ -0,0 +1,140 @@ +package org.programmers.springboot.basic.domain.voucher.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherControllerRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; +import org.programmers.springboot.basic.domain.voucher.exception.DuplicateVoucherException; +import org.programmers.springboot.basic.domain.voucher.exception.IllegalDiscountException; +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; +import org.programmers.springboot.basic.domain.voucher.mapper.VoucherMapper; +import org.programmers.springboot.basic.domain.voucher.service.VoucherService; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Slf4j +@Controller +@RequiredArgsConstructor +@RequestMapping("/voucher") +public class VoucherWebController { + + private final VoucherService voucherService; + + @GetMapping("/createForm") + public String createVoucher() { + return "voucher/createForm"; + } + + @GetMapping("/findForm") + public String findVoucher() { + return "voucher/findForm"; + } + + @GetMapping("/updateForm") + public String updateVoucher() { + return "voucher/updateForm"; + } + + @GetMapping("/deleteForm") + public String deleteVoucher() { + return "voucher/deleteForm"; + } + + @PostMapping("/create") + public String create(VoucherControllerRequestDto requestDto, Model model) { + + VoucherType voucherType = null; + Long discount = null; + try { + voucherType = VoucherType.valueOf(Integer.parseInt(requestDto.getVoucherType())); + discount = Long.parseLong(requestDto.getDiscount()); + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE.mapToRequestDto(voucherType, discount); + voucherService.create(voucherRequestDto); + return "redirect:/"; + } catch (NumberFormatException e) { + log.error("your input is Invalid Discount Type '{}'", discount); + model.addAttribute("err", e.getMessage()); + } catch (IllegalDiscountException e) { + log.error("your input is Invalid Discount Range '{}'", discount); + model.addAttribute("err", e.getMessage()); + } catch (DuplicateVoucherException e) { + log.warn("voucher of voucherType '{}' and discount '{} is already exists", + voucherType, discount); + model.addAttribute("err", e.getMessage()); + } catch (VoucherNotFoundException e) { + log.warn("No matching voucher of voucherType '{}' found", voucherType); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } + + @GetMapping("/find") + public String find(@RequestParam String voucherId, Model model) { + try { + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(voucherId); + VoucherResponseDto voucherResponseDto = voucherService.findById(voucherRequestDto); + model.addAttribute("voucher", voucherResponseDto); + return "voucher/find"; + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", voucherId); + model.addAttribute("err", e.getMessage()); + } catch (VoucherNotFoundException e) { + log.warn("No voucher found for voucherId: '{}'", voucherId); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } + + @PutMapping("/update") + public String update(VoucherControllerRequestDto requestDto, Model model) { + String voucherId = null; + Long discount = null; + try { + voucherId = requestDto.getVoucherId(); + discount = Long.parseLong(requestDto.getDiscount()); + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithIdNDiscount(voucherId, discount); + voucherService.updateVoucher(voucherRequestDto); + return "redirect:/"; + } catch (NumberFormatException e) { + log.error("Your input is Invalid Type of Long: '{}'", discount); + model.addAttribute("err", e.getMessage()); + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", voucherId); + model.addAttribute("err", e.getMessage()); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", voucherId); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } + + @DeleteMapping("/delete") + public String delete(VoucherControllerRequestDto requestDto, Model model) { + String voucherId = null; + try { + voucherId = requestDto.getVoucherId(); + VoucherRequestDto voucherRequestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(voucherId); + voucherService.deleteVoucher(voucherRequestDto); + return "redirect:/"; + } catch (IllegalArgumentException e) { + log.error("Your input is Invalid UUID string: '{}'", voucherId); + model.addAttribute("err", e.getMessage()); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", voucherId); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } + + @GetMapping("/list") + public String list(Model model) { + List vouchers = voucherService.findAll(); + model.addAttribute("vouchers", vouchers); + return "voucher/voucherList"; + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherControllerRequestDto.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherControllerRequestDto.java new file mode 100644 index 0000000000..cc23fa9a23 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherControllerRequestDto.java @@ -0,0 +1,14 @@ +package org.programmers.springboot.basic.domain.voucher.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class VoucherControllerRequestDto { + + private final String voucherId; + private final String discount; + private final String voucherType; + private final String createdAt; +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherRequestDto.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherRequestDto.java new file mode 100644 index 0000000000..f69f17313b --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherRequestDto.java @@ -0,0 +1,33 @@ +package org.programmers.springboot.basic.domain.voucher.dto; + +import lombok.Builder; +import lombok.Getter; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; + +import java.time.LocalDateTime; +import java.util.UUID; + +@Builder +@Getter +public class VoucherRequestDto { + + private final UUID voucherId; + private final VoucherType voucherType; + private final Long discount; + private final LocalDateTime createdAt; + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherResponseDto.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherResponseDto.java new file mode 100644 index 0000000000..b25ca38ff6 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/dto/VoucherResponseDto.java @@ -0,0 +1,43 @@ +package org.programmers.springboot.basic.domain.voucher.dto; + +import lombok.Builder; +import lombok.Getter; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; + +import java.time.LocalDateTime; +import java.util.UUID; + +@Builder +@Getter +public class VoucherResponseDto { + + private final UUID voucherId; + private final VoucherType voucherType; + private final Long discount; + private final LocalDateTime createdAt; + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } + + public String printInfo() { + return String.format(""" + === Voucher === + VoucherID: %s + Discount: %d + VoucherType: %s + CreatedAt: %s + """, voucherId.toString(), discount, voucherType, createdAt.toString()); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/entity/Voucher.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/entity/Voucher.java new file mode 100644 index 0000000000..2fac4ac961 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/entity/Voucher.java @@ -0,0 +1,31 @@ +package org.programmers.springboot.basic.domain.voucher.entity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.programmers.springboot.basic.domain.voucher.service.validate.VoucherValidationStrategy; + +import java.time.LocalDateTime; +import java.util.UUID; + +@Getter +@AllArgsConstructor +public class Voucher { + + private final UUID voucherId; + private final VoucherType voucherType; + private final Long discount; + private final LocalDateTime createdAt; + private VoucherValidationStrategy validationStrategy; + + public void setValidationStrategy(VoucherValidationStrategy validationStrategy) { + this.validationStrategy = validationStrategy; + } + + public int getVoucherTypeValue() { + return this.voucherType.getValue(); + } + + public void validate() { + validationStrategy.validate(this.discount); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/entity/VoucherType.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/entity/VoucherType.java new file mode 100644 index 0000000000..dbcdadef9d --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/entity/VoucherType.java @@ -0,0 +1,29 @@ +package org.programmers.springboot.basic.domain.voucher.entity; + +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; + +import java.util.Arrays; + +public enum VoucherType { + + FIXED(1), + PERCENT(2); + + private final int value; + + VoucherType(int value) { + this.value = value; + } + + public int getValue() { + return this.value; + } + + public static VoucherType valueOf(int value) { + + return Arrays.stream(values()) + .filter(voucher -> voucher.getValue() == value) + .findAny() + .orElseThrow(VoucherNotFoundException::new); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/DuplicateVoucherException.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/DuplicateVoucherException.java new file mode 100644 index 0000000000..6fc7c5ad20 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/DuplicateVoucherException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.voucher.exception; + +public class DuplicateVoucherException extends RuntimeException { + + public DuplicateVoucherException() { + super("Duplicate voucher already exists!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/IllegalDiscountException.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/IllegalDiscountException.java new file mode 100644 index 0000000000..2c5eecb56f --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/IllegalDiscountException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.voucher.exception; + +public class IllegalDiscountException extends RuntimeException { + + public IllegalDiscountException(String msg) { + super(msg); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/VoucherNotFoundException.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/VoucherNotFoundException.java new file mode 100644 index 0000000000..58a2b6ec8c --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/VoucherNotFoundException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.voucher.exception; + +public class VoucherNotFoundException extends RuntimeException { + + public VoucherNotFoundException() { + super("No matching vouchers found!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/VoucherValidatorNotFoundException.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/VoucherValidatorNotFoundException.java new file mode 100644 index 0000000000..d59ba628f9 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/exception/VoucherValidatorNotFoundException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.voucher.exception; + +public class VoucherValidatorNotFoundException extends RuntimeException { + + public VoucherValidatorNotFoundException() { + super("No matching validator found!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/mapper/VoucherMapper.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/mapper/VoucherMapper.java new file mode 100644 index 0000000000..3f02c1eb28 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/mapper/VoucherMapper.java @@ -0,0 +1,92 @@ +package org.programmers.springboot.basic.domain.voucher.mapper; + +import org.mapstruct.*; +import org.mapstruct.factory.Mappers; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherControllerRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.Voucher; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; +import org.programmers.springboot.basic.domain.voucher.service.validate.VoucherValidationStrategy; +import org.programmers.springboot.basic.util.generator.DateTimeGenerator; +import org.programmers.springboot.basic.util.generator.UUIDGenerator; + +import java.time.LocalDateTime; +import java.util.Map; +import java.util.UUID; + +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface VoucherMapper { + + VoucherMapper INSTANCE = Mappers.getMapper(VoucherMapper.class); + + @Mapping(target = "voucherId", expression = "java(mapToUUID(voucherId))") + @Mapping(target = "voucherType", expression = "java(mapToVoucherType(voucherType))") + @Mapping(target = "discount", expression = "java(mapToLong(discount))") + @Mapping(target = "createdAt", expression = "java(mapToDateTime(createdAt))") + VoucherRequestDto mapToRequestDtoWithAllArgs(String voucherId, String voucherType, String discount, String createdAt); + + @Mapping(target = "voucherId", expression = "java(mapToUUID(requestDto.getVoucherId()))") + @Mapping(target = "voucherType", expression = "java(mapToVoucherType(requestDto.getVoucherType()))") + @Mapping(target = "discount", expression = "java(mapToLong(requestDto.getDiscount()))") + @Mapping(target = "createdAt", expression = "java(mapToDateTime(requestDto.getCreatedAt()))") + VoucherRequestDto mapToRequestDtoWithControllerDto(VoucherControllerRequestDto requestDto); + + @Mapping(target = "voucherType", source = "voucherType") + @Mapping(target = "discount", source = "discount") + VoucherRequestDto mapToRequestDto(VoucherType voucherType, Long discount); + + @Mapping(target = "voucherId", expression = "java(mapToUUID(voucherId))") + @Mapping(target = "discount", source = "discount") + VoucherRequestDto mapToRequestDtoWithIdNDiscount(String voucherId, Long discount); + + @Mapping(target = "voucherId", expression = "java(mapToUUID(voucherId))") + VoucherRequestDto mapToRequestDtoWithUUID(String voucherId); + + @Mapping(target = "voucherId", expression = "java(generateUUID(uuidGenerator))") + @Mapping(target = "createdAt", expression = "java(generateDateTime(dateTimeGenerator))") + Voucher mapToEntityWithGenerator(VoucherRequestDto requestDto, @Context UUIDGenerator uuidGenerator, + @Context DateTimeGenerator dateTimeGenerator, + @Context Map validationStrategyMap); + + VoucherResponseDto mapToResponseDto(Voucher voucher); + + Voucher mapToEntity(VoucherRequestDto voucherRequestDto); + + default UUID mapToUUID(String voucherId) { + return voucherId != null ? UUID.fromString(voucherId) : null; + } + + default LocalDateTime mapToDateTime(String createdAt) { + return createdAt != null ? LocalDateTime.parse(createdAt) : null; + } + + default Long mapToLong(String discount) { + return discount != null ? Long.parseLong(discount) : null; + } + + default VoucherType mapToVoucherType(String voucherType) { + return voucherType != null ? VoucherType.valueOf(voucherType) : null; + } + + default UUID generateUUID(@Context UUIDGenerator uuidGenerator) { + return uuidGenerator.generateUUID(); + } + + default LocalDateTime generateDateTime(@Context DateTimeGenerator dateTimeGenerator) { + return dateTimeGenerator.generateDateTime(); + } + + default VoucherValidationStrategy generateValidator(VoucherType voucherType, @Context Map validationStrategyMap) { + return validationStrategyMap.get(voucherType); + } + + @AfterMapping + default void setValidationStrategy(@MappingTarget Voucher voucher, + VoucherRequestDto requestDto, + @Context Map validationStrategyMap) { + VoucherType voucherType = requestDto.getVoucherType(); + VoucherValidationStrategy strategy = validationStrategyMap.get(voucherType); + voucher.setValidationStrategy(strategy); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/repository/JdbcVoucherRepository.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/repository/JdbcVoucherRepository.java new file mode 100644 index 0000000000..ad9e4f3151 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/repository/JdbcVoucherRepository.java @@ -0,0 +1,131 @@ +package org.programmers.springboot.basic.domain.voucher.repository; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.voucher.entity.Voucher; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; +import org.programmers.springboot.basic.domain.voucher.service.validate.VoucherValidationStrategy; +import org.programmers.springboot.basic.util.converter.UUIDConverter; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +@Slf4j +@Repository +@RequiredArgsConstructor +public class JdbcVoucherRepository implements VoucherRepository { + private final JdbcTemplate jdbcTemplate; + private final Map validationStrategyMap; + + private RowMapper voucherRowMapper() { + return (rs, rowNum) -> { + UUID voucherId = UUIDConverter.toUUID(rs.getBytes("voucher_id")); + VoucherType voucherType = VoucherType.valueOf(rs.getInt("voucher_type")); + Long discount = rs.getLong("discount"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + LocalDateTime createdAt = LocalDateTime.parse(rs.getString("createdAt"), formatter); + return new Voucher(voucherId, voucherType, discount, createdAt, validationStrategyMap.get(voucherType)); + }; + } + + @Override + public void save(final Voucher voucher) { + String sql = "INSERT INTO vouchers(voucher_id, voucher_type, discount) VALUES(UUID_TO_BIN(?), ?, ?)"; + this.jdbcTemplate.update(sql, + UUIDConverter.toBytes(voucher.getVoucherId()), + voucher.getVoucherTypeValue(), + voucher.getDiscount()); + } + + @Override + public Optional findById(UUID voucherId) { + String sql = "SELECT * FROM vouchers WHERE voucher_id = UUID_TO_BIN(?)"; + try { + return Optional.ofNullable(this.jdbcTemplate.queryForObject(sql, voucherRowMapper(), + (Object) UUIDConverter.toBytes(voucherId))); + } catch (EmptyResultDataAccessException e) { + log.warn("No voucher found for voucherId: {}", voucherId); + } catch (DataAccessException e) { + log.error("Data access exception: {}", e.toString()); + } + return Optional.empty(); + } + + @Override + public List find(UUID voucherId, VoucherType voucherType, Long discount, LocalDateTime createdAt) { + String sql = "SELECT * FROM vouchers WHERE " + + "(voucher_id = UUID_TO_BIN(?) OR UUID_TO_BIN(?) IS NULL) " + + "AND (voucher_type = ? OR ? IS NULL) " + + "AND (discount = ? OR ? IS NULL) " + + "AND (createdAt = ? OR ? IS NULL)"; + + byte[] bytes = getNullableBytes(voucherId); + Integer type = getNullableValue(voucherType); + Timestamp timestamp = getNullableTimestamp(createdAt); + return this.jdbcTemplate.query(sql, voucherRowMapper(), + bytes, bytes, + type, type, + discount, discount, + timestamp, timestamp); + } + + private byte[] getNullableBytes(UUID value) { + return value != null ? UUIDConverter.toBytes(value) : null; + } + + private Integer getNullableValue(VoucherType value) { + return value != null ? value.getValue() : null; + } + + private Timestamp getNullableTimestamp(LocalDateTime value) { + return value != null ? Timestamp.valueOf(value) : null; + } + + @Override + public Optional findByTypeNDiscount(VoucherType voucherType, Long discount) { + String sql = "SELECT * FROM vouchers WHERE voucher_type = ? AND discount = ?"; + try { + return Optional.ofNullable(this.jdbcTemplate.queryForObject(sql, voucherRowMapper(), + voucherType.getValue(), discount)); + } catch (EmptyResultDataAccessException e) { + log.warn("No voucher found for voucherType {} and discount {}", voucherType, discount); + } catch (DataAccessException e) { + log.error("Data access exception: {}", e.toString()); + } + return Optional.empty(); + } + + @Override + public List findAll() { + String sql = "SELECT * FROM vouchers ORDER BY voucher_id"; + return this.jdbcTemplate.query(sql, voucherRowMapper()); + } + + @Override + public void update(Voucher voucher) { + String sql = "UPDATE vouchers SET discount = ? WHERE voucher_id = UUID_TO_BIN(?)"; + this.jdbcTemplate.update(sql, voucher.getDiscount(), UUIDConverter.toBytes(voucher.getVoucherId())); + } + + @Override + public void delete(UUID voucherId) { + String sql = "DELETE FROM vouchers WHERE voucher_id = UUID_TO_BIN(?)"; + this.jdbcTemplate.update(sql, (Object) UUIDConverter.toBytes(voucherId)); + } + + @Override + public void deleteAll() { + String sql = "DELETE FROM vouchers"; + this.jdbcTemplate.update(sql); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/repository/VoucherRepository.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/repository/VoucherRepository.java new file mode 100644 index 0000000000..c56c24954a --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/repository/VoucherRepository.java @@ -0,0 +1,22 @@ +package org.programmers.springboot.basic.domain.voucher.repository; + +import org.programmers.springboot.basic.domain.voucher.entity.Voucher; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface VoucherRepository { + + void save(Voucher voucher); + Optional findById(UUID voucherId); + List find(UUID voucherId, VoucherType voucherType, Long discount, LocalDateTime createdAt); + Optional findByTypeNDiscount(VoucherType voucherType, Long discount); + List findAll(); + void update(Voucher voucher); + void delete(UUID voucherId); + void deleteAll(); + +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/service/VoucherService.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/VoucherService.java new file mode 100644 index 0000000000..ef24d2f34d --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/VoucherService.java @@ -0,0 +1,125 @@ +package org.programmers.springboot.basic.domain.voucher.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.Voucher; +import org.programmers.springboot.basic.domain.voucher.entity.VoucherType; +import org.programmers.springboot.basic.domain.voucher.exception.DuplicateVoucherException; +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; +import org.programmers.springboot.basic.domain.voucher.mapper.VoucherMapper; +import org.programmers.springboot.basic.util.generator.DateTimeGenerator; +import org.programmers.springboot.basic.util.generator.UUIDGenerator; +import org.programmers.springboot.basic.domain.voucher.repository.VoucherRepository; +import org.programmers.springboot.basic.domain.voucher.service.validate.VoucherValidationStrategy; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@Profile("default") +@Slf4j +@Service +@RequiredArgsConstructor +public class VoucherService { + + private final VoucherRepository voucherRepository; + private final UUIDGenerator uuidGenerator; + private final DateTimeGenerator dateTimeGenerator; + private final Map validationStrategyMap; + + @Transactional + public void create(VoucherRequestDto voucherRequestDto) { + + Long discount = voucherRequestDto.getDiscount(); + VoucherType voucherType = voucherRequestDto.getVoucherType(); + + Voucher voucher = VoucherMapper.INSTANCE.mapToEntityWithGenerator(voucherRequestDto, + uuidGenerator, + dateTimeGenerator, + validationStrategyMap); + voucher.validate(); + if (isDuplicate(voucher)) { + log.warn("voucher of voucherType '{}' and discount '{}' is already exists", voucherType, discount); + throw new DuplicateVoucherException(); + } + voucherRepository.save(voucher); + } + + private boolean isDuplicate(Voucher voucher) { + return voucherRepository.findByTypeNDiscount(voucher.getVoucherType(), voucher.getDiscount()).isPresent(); + } + + public List findAll() { + + List vouchers = getAll(); + return vouchers.stream() + .map(VoucherMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + public VoucherResponseDto findById(VoucherRequestDto voucherRequestDto) { + + UUID voucherId = voucherRequestDto.getVoucherId(); + + Voucher voucher = get(voucherId); + return VoucherMapper.INSTANCE.mapToResponseDto(voucher); + } + + public List findByOption(VoucherRequestDto voucherRequestDto) { + + UUID voucherId = voucherRequestDto.getVoucherId(); + VoucherType voucherType = voucherRequestDto.getVoucherType(); + Long discount = voucherRequestDto.getDiscount(); + LocalDateTime createdAt = voucherRequestDto.getCreatedAt(); + List vouchers = getByOption(voucherId, voucherType, discount, createdAt); + return vouchers.stream() + .map(VoucherMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + @Transactional + public void deleteVoucher(VoucherRequestDto voucherRequestDto) { + VoucherResponseDto voucherResponseDto = findById(voucherRequestDto); + delete(voucherResponseDto.getVoucherId()); + } + + @Transactional + public void updateVoucher(VoucherRequestDto voucherRequestDto) { + Voucher voucher = VoucherMapper.INSTANCE.mapToEntity(voucherRequestDto); + voucherRepository.update(voucher); + } + + private Voucher get(UUID voucherId) { + return voucherRepository.findById(voucherId) + .orElseThrow(() -> { + log.warn("No voucher found for voucherId: {}" , voucherId); + return new VoucherNotFoundException(); + }); + } + + private List getByOption(UUID voucherId, + VoucherType voucherType, + Long discount, + LocalDateTime createdAt) { + return voucherRepository.find(voucherId, voucherType, discount, createdAt); + } + + private List getAll() { + return voucherRepository.findAll(); + } + + private void delete(UUID voucherId) { + voucherRepository.delete(voucherId); + } + + @Transactional + public void deleteAll() { + voucherRepository.deleteAll(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/FixedAmountVoucherValidationStrategy.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/FixedAmountVoucherValidationStrategy.java new file mode 100644 index 0000000000..fd6e5a9364 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/FixedAmountVoucherValidationStrategy.java @@ -0,0 +1,14 @@ +package org.programmers.springboot.basic.domain.voucher.service.validate; + +import org.programmers.springboot.basic.AppConstants; +import org.programmers.springboot.basic.domain.voucher.exception.IllegalDiscountException; + +public class FixedAmountVoucherValidationStrategy implements VoucherValidationStrategy { + + @Override + public void validate(Long discount) { + if (discount < AppConstants.MIN_FIXED_DISCOUNT) { + throw new IllegalDiscountException("Exception Occurred: Illegal Discount value! Possible from 0."); + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/PercentDiscountVoucherValidationStrategy.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/PercentDiscountVoucherValidationStrategy.java new file mode 100644 index 0000000000..888af2c1bf --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/PercentDiscountVoucherValidationStrategy.java @@ -0,0 +1,14 @@ +package org.programmers.springboot.basic.domain.voucher.service.validate; + +import org.programmers.springboot.basic.AppConstants; +import org.programmers.springboot.basic.domain.voucher.exception.IllegalDiscountException; + +public class PercentDiscountVoucherValidationStrategy implements VoucherValidationStrategy { + + @Override + public void validate(Long discount) { + if (discount < AppConstants.MIN_PERCENT_DISCOUNT || discount > AppConstants.MAX_PERCENT_DISCOUNT) { + throw new IllegalDiscountException("Exception Occurred: Illegal Discount value! Possible from 0 to 100."); + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/VoucherValidationStrategy.java b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/VoucherValidationStrategy.java new file mode 100644 index 0000000000..41c91c4a7f --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/voucher/service/validate/VoucherValidationStrategy.java @@ -0,0 +1,5 @@ +package org.programmers.springboot.basic.domain.voucher.service.validate; + +public interface VoucherValidationStrategy { + void validate(Long discount); +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/controller/WalletController.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/controller/WalletController.java new file mode 100644 index 0000000000..6a523caafc --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/controller/WalletController.java @@ -0,0 +1,125 @@ +package org.programmers.springboot.basic.domain.wallet.controller; + +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.dto.CustomerResponseDto; +import org.programmers.springboot.basic.domain.customer.entity.Customer; +import org.programmers.springboot.basic.domain.customer.exception.CustomerNotFoundException; +import org.programmers.springboot.basic.domain.customer.exception.IllegalEmailException; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.Voucher; +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; +import org.programmers.springboot.basic.domain.wallet.dto.WalletRequestDto; +import org.programmers.springboot.basic.domain.wallet.dto.WalletResponseDto; +import org.programmers.springboot.basic.domain.wallet.exception.DuplicateWalletException; +import org.programmers.springboot.basic.domain.wallet.mapper.WalletMapper; +import org.programmers.springboot.basic.domain.wallet.service.WalletService; +import org.programmers.springboot.basic.util.manager.ConsoleIOManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; + +import java.util.List; + +@Slf4j +@Controller +public class WalletController { + + private final ConsoleIOManager consoleIOManager; + private final WalletService walletService; + + @Autowired + public WalletController(ConsoleIOManager consoleIOManager, WalletService walletService) { + this.consoleIOManager = consoleIOManager; + this.walletService = walletService; + } + + public void addWallet() { + + String email = null; + String voucherId = null; + + consoleIOManager.printAssignHandler(); + + try { + email = consoleIOManager.getInput(); + voucherId = consoleIOManager.getInput(); + + WalletRequestDto requestDto = WalletMapper.INSTANCE.mapToRequestDto(email, voucherId); + this.walletService.createWallet(requestDto); + } catch (IllegalArgumentException e) { + log.warn("Your input is Invalid UUID string: '{}'", voucherId); + } catch (IllegalEmailException e) { + log.warn("Your input is Invalid Email Type: '{}'", email); + } catch (DuplicateWalletException e) { + log.warn("email '{}' and voucherId '{}' is already exists in Wallet", email, voucherId); + } catch (CustomerNotFoundException e) { + log.warn("No customer of email '{}' found", email); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", voucherId); + } + } + + public void findVoucherListByEmail() { + + String email = null; + + consoleIOManager.printListByConsumerHandler(); + + try { + email = consoleIOManager.getInput(); + + WalletRequestDto requestDto = WalletMapper.INSTANCE.mapToRequestDtoWithEmail(email); + List walletResponseDtos = this.walletService.walletListByEmail(requestDto); + List voucherResponseDtos = this.walletService.voucherListFromWallet(walletResponseDtos); + Customer customer = this.walletService.findCustomerByEmail(requestDto); + consoleIOManager.printWalletInfoByConsumer(customer, voucherResponseDtos); + } catch (IllegalEmailException e) { + log.warn("Your input is Invalid Email Type: '{}'", email); + } catch (CustomerNotFoundException e) { + log.warn("No customer of email '{}' found", email); + } + } + + + public void findCustomerListByVoucherId() { + + String input = null; + + consoleIOManager.printListByVoucherHandler(); + + try { + input = consoleIOManager.getInput(); + WalletRequestDto requestDto = WalletMapper.INSTANCE.mapToRequestDtoWithUUID(input); + List walletResponseDtos = this.walletService.walletListByVoucherId(requestDto); + List customerResponseDtos = this.walletService.customerListFromWallet(walletResponseDtos); + Voucher voucher = this.walletService.findVoucherById(requestDto); + consoleIOManager.printWalletInfoByVoucher(voucher, customerResponseDtos); + } catch (IllegalArgumentException e) { + log.warn("Your input is Invalid UUID string: '{}'", input); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", input); + } + } + + public void removeVoucherFromWallet() { + + String email = null; + String voucherId = null; + + consoleIOManager.printRemoveVoucherFromWalletHandler(); + + try { + email = consoleIOManager.getInput(); + voucherId = consoleIOManager.getInput(); + WalletRequestDto requestDto = WalletMapper.INSTANCE.mapToRequestDto(email, voucherId); + this.walletService.removeVoucherFromWallet(requestDto); + } catch (IllegalArgumentException e) { + log.warn("Your input is Invalid UUID string: '{}'", voucherId); + } catch (IllegalEmailException e) { + log.warn("Your input is Invalid Email Type: '{}'", email); + } catch (CustomerNotFoundException e) { + log.warn("No customer of email '{}' found", email); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", voucherId); + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/controller/WalletWebController.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/controller/WalletWebController.java new file mode 100644 index 0000000000..24a7c71160 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/controller/WalletWebController.java @@ -0,0 +1,164 @@ +package org.programmers.springboot.basic.domain.wallet.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.dto.CustomerResponseDto; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.domain.customer.exception.CustomerNotFoundException; +import org.programmers.springboot.basic.domain.customer.exception.IllegalEmailException; +import org.programmers.springboot.basic.domain.customer.service.CustomerService; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherRequestDto; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; +import org.programmers.springboot.basic.domain.voucher.mapper.VoucherMapper; +import org.programmers.springboot.basic.domain.voucher.service.VoucherService; +import org.programmers.springboot.basic.domain.wallet.dto.WalletControllerRequestDto; +import org.programmers.springboot.basic.domain.wallet.dto.WalletRequestDto; +import org.programmers.springboot.basic.domain.wallet.dto.WalletResponseDto; +import org.programmers.springboot.basic.domain.wallet.exception.DuplicateWalletException; +import org.programmers.springboot.basic.domain.wallet.mapper.WalletMapper; +import org.programmers.springboot.basic.domain.wallet.service.WalletService; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; + +@Slf4j +@Controller +@RequiredArgsConstructor +@RequestMapping("/wallet") +public class WalletWebController { + + private final WalletService walletService; + private final VoucherService voucherService; + private final CustomerService customerService; + + @GetMapping("/addForm") + public String addWallet(Model model) { + model.addAttribute("vouchers", voucherService.findAll()); + return "wallet/addForm"; + } + + @GetMapping("/deleteForm") + public String removeWallet() { + return "wallet/deleteForm"; + } + + @GetMapping("/findVoucherForm") + public String findAllVoucher() { + return "wallet/findVoucherForm"; + } + + @GetMapping("/findCustomerForm") + public String findAllCustomer() { + return "wallet/findCustomerForm"; + } + + @PostMapping("/add") + public String addVoucherInWallet(WalletControllerRequestDto requestDto, Model model) { + + String voucherId = null; + String email = null; + try { + voucherId = requestDto.getVoucherId(); + email = requestDto.getEmail(); + + WalletRequestDto walletRequestDto = WalletMapper.INSTANCE.mapToRequestDto(voucherId, email); + walletService.createWallet(walletRequestDto); + return "redirect:/"; + } catch (IllegalArgumentException e) { + log.warn("Your input is Invalid UUID string: '{}'", voucherId); + model.addAttribute("err", e.getMessage()); + } catch (IllegalEmailException e) { + log.warn("Your input is Invalid Email Type: '{}'", email); + model.addAttribute("err", e.getMessage()); + } catch (DuplicateWalletException e) { + log.warn("email '{}' and voucherId '{}' is already exists in Wallet", email, voucherId); + model.addAttribute("err", e.getMessage()); + } catch (CustomerNotFoundException e) { + log.warn("No customer of email '{}' found", email); + model.addAttribute("err", e.getMessage()); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", voucherId); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } + + @DeleteMapping("/delete") + public String removeWallet(WalletControllerRequestDto requestDto, Model model) { + + String voucherId = null; + String email = null; + try { + voucherId = requestDto.getVoucherId(); + email = requestDto.getEmail(); + + WalletRequestDto walletRequestDto = WalletMapper.INSTANCE.mapToRequestDto(voucherId, email); + walletService.removeVoucherFromWallet(walletRequestDto); + return "redirect:/"; + } catch (IllegalArgumentException e) { + log.warn("Your input is Invalid UUID string: '{}'", voucherId); + model.addAttribute("err", e.getMessage()); + } catch (IllegalEmailException e) { + log.warn("Your input is Invalid Email Type: '{}'", email); + model.addAttribute("err", e.getMessage()); + } catch (CustomerNotFoundException e) { + log.warn("No customer of email '{}' found", email); + model.addAttribute("err", e.getMessage()); + } catch (VoucherNotFoundException e) { + log.warn("No voucher of voucherId '{}' found", voucherId); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } + + @GetMapping("/vouchers") + public String voucherListInWallet(@RequestParam String email, Model model) { + + try { + WalletRequestDto walletRequestDto = WalletMapper.INSTANCE.mapToRequestDtoWithEmail(email); + List wallets = walletService.walletListByEmail(walletRequestDto); + CustomerResponseDto customerResponseDto = customerService.findByEmail(Email.valueOf(email)); + + List vouchers = new ArrayList<>(); + for (WalletResponseDto wallet: wallets) { + vouchers.add(voucherService.findById(VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(wallet.getVoucherId().toString()))); + } + + model.addAttribute("customer", customerResponseDto); + model.addAttribute("vouchers", vouchers); + return "wallet/voucherListInWallet"; + } catch (Exception e) { + log.error(e.toString()); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } + + @GetMapping("/customers") + public String customerListInWallet(@RequestParam String voucherId, Model model) { + + try { + WalletRequestDto walletRequestDto = WalletMapper.INSTANCE.mapToRequestDtoWithUUID(voucherId); + List wallets = walletService.walletListByVoucherId(walletRequestDto); + VoucherRequestDto requestDto = VoucherMapper.INSTANCE.mapToRequestDtoWithUUID(voucherId); + VoucherResponseDto voucherResponseDto = voucherService.findById(requestDto); + + List customers = new ArrayList<>(); + for (WalletResponseDto wallet : wallets) { + customers.add(customerService.findByEmail(wallet.getEmail())); + } + + model.addAttribute("voucher", voucherResponseDto); + model.addAttribute("customers", customers); + return "wallet/customerListInWallet"; + } catch (Exception e) { + log.error(e.toString()); + model.addAttribute("err", e.getMessage()); + } + return "error"; + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletControllerRequestDto.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletControllerRequestDto.java new file mode 100644 index 0000000000..a582e28660 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletControllerRequestDto.java @@ -0,0 +1,12 @@ +package org.programmers.springboot.basic.domain.wallet.dto; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public class WalletControllerRequestDto { + + private final String voucherId; + private final String email; +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletRequestDto.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletRequestDto.java new file mode 100644 index 0000000000..935d5deabd --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletRequestDto.java @@ -0,0 +1,30 @@ +package org.programmers.springboot.basic.domain.wallet.dto; + +import lombok.Builder; +import lombok.Getter; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; + +import java.util.UUID; + +@Builder +@Getter +public class WalletRequestDto { + + private final Email email; + private final UUID voucherId; + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletResponseDto.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletResponseDto.java new file mode 100644 index 0000000000..0cfd4ac074 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/dto/WalletResponseDto.java @@ -0,0 +1,30 @@ +package org.programmers.springboot.basic.domain.wallet.dto; + +import lombok.Builder; +import lombok.Getter; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; + +import java.util.UUID; + +@Builder +@Getter +public class WalletResponseDto { + + private final Email email; + private final UUID voucherId; + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public String toString() { + return super.toString(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/entity/Wallet.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/entity/Wallet.java new file mode 100644 index 0000000000..c12176bf7e --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/entity/Wallet.java @@ -0,0 +1,17 @@ +package org.programmers.springboot.basic.domain.wallet.entity; + +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; + +import java.util.UUID; + +@Getter +@Builder +@RequiredArgsConstructor +public class Wallet { + + private final UUID voucherId; + private final Email email; +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/exception/DuplicateWalletException.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/exception/DuplicateWalletException.java new file mode 100644 index 0000000000..9838f0d623 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/exception/DuplicateWalletException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.domain.wallet.exception; + +public class DuplicateWalletException extends RuntimeException { + + public DuplicateWalletException() { + super("Duplicate value already exists in wallet!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/mapper/WalletMapper.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/mapper/WalletMapper.java new file mode 100644 index 0000000000..e7dd286f61 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/mapper/WalletMapper.java @@ -0,0 +1,44 @@ +package org.programmers.springboot.basic.domain.wallet.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.ReportingPolicy; +import org.mapstruct.factory.Mappers; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.domain.wallet.dto.WalletRequestDto; +import org.programmers.springboot.basic.domain.wallet.dto.WalletResponseDto; +import org.programmers.springboot.basic.domain.wallet.entity.Wallet; + +import java.util.UUID; + +@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface WalletMapper { + + WalletMapper INSTANCE = Mappers.getMapper(WalletMapper.class); + + @Mapping(target = "voucherId", expression = "java(mapToUUID(voucherId))") + @Mapping(target = "email", expression = "java(mapToEmail(email))") + WalletRequestDto mapToRequestDto(String voucherId, String email); + + @Mapping(target = "voucherId", source = "voucherId") + @Mapping(target = "email", source = "email") + Wallet mapToEntity(UUID voucherId, Email email); + + @Mapping(target = "email", source = "email") + WalletRequestDto mapToRequestDtoWithEmail(String email); + + @Mapping(target = "voucherId", expression = "java(mapToUUID(voucherId))") + WalletRequestDto mapToRequestDtoWithUUID(String voucherId); + + Wallet mapToEntity(WalletRequestDto walletRequestDto); + + WalletResponseDto mapToResponseDto(Wallet wallet); + + default UUID mapToUUID(String value) { + return UUID.fromString(value); + } + + default Email mapToEmail(String value) { + return Email.valueOf(value); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/repository/JdbcWalletRepository.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/repository/JdbcWalletRepository.java new file mode 100644 index 0000000000..d62b66bbc8 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/repository/JdbcWalletRepository.java @@ -0,0 +1,79 @@ +package org.programmers.springboot.basic.domain.wallet.repository; + +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.domain.wallet.entity.Wallet; +import org.programmers.springboot.basic.util.converter.UUIDConverter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Repository; + +import javax.sql.DataSource; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Slf4j +@Repository +public class JdbcWalletRepository implements WalletRepository { + + private final JdbcTemplate jdbcTemplate; + + @Autowired + public JdbcWalletRepository(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } + + public RowMapper walletRowMapper() { + return (rs, rowNum) -> { + UUID voucherId = UUIDConverter.toUUID(rs.getBytes("voucher_id")); + Email email = Email.valueOf(rs.getString("email")); + return new Wallet(voucherId, email); + }; + } + @Override + public void save(Wallet wallet) { + String sql = "INSERT INTO wallets (email, voucher_id) VALUES(?, UUID_TO_BIN(?))"; + this.jdbcTemplate.update(sql, wallet.getEmail().getEmail(), UUIDConverter.toBytes(wallet.getVoucherId())); + } + + @Override + public List findByEmail(Email email) { + String sql = "SELECT * FROM wallets WHERE email = ?"; + return this.jdbcTemplate.query(sql, walletRowMapper(), email.getEmail()); + } + + @Override + public List findById(UUID voucherId) { + String sql = "SELECT * FROM wallets WHERE voucher_id = UUID_TO_BIN(?)"; + return this.jdbcTemplate.query(sql, walletRowMapper(), (Object) UUIDConverter.toBytes(voucherId)); + } + @Override + public Optional findByEmailNId(Email email, UUID voucherId) { + String sql = "SELECT * FROM wallets WHERE email = ? AND voucher_id = UUID_TO_BIN(?)"; + try { + return Optional.ofNullable(this.jdbcTemplate.queryForObject(sql, walletRowMapper(), + email.getEmail(), UUIDConverter.toBytes(voucherId))); + } catch (EmptyResultDataAccessException e) { + log.warn("No customer found for email and voucherId: {}, {}", email.getEmail(), voucherId); + } catch (DataAccessException e) { + log.error("Data access exception: {}", e.toString()); + } + return Optional.empty(); + } + + @Override + public void delete(Wallet wallet) { + String sql = "DELETE FROM wallets WHERE email = ? AND voucher_id = UUID_TO_BIN(?)"; + this.jdbcTemplate.update(sql, wallet.getEmail().getEmail(), UUIDConverter.toBytes(wallet.getVoucherId())); + } + + @Override + public void deleteAll() { + String sql = "TRUNCATE TABLE wallets"; + this.jdbcTemplate.execute(sql); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/repository/WalletRepository.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/repository/WalletRepository.java new file mode 100644 index 0000000000..a77f17a9d3 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/repository/WalletRepository.java @@ -0,0 +1,18 @@ +package org.programmers.springboot.basic.domain.wallet.repository; + +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.domain.wallet.entity.Wallet; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface WalletRepository { + + void save(Wallet wallet); + List findByEmail(Email email); + List findById(UUID voucherId); + Optional findByEmailNId(Email email, UUID voucherId); + void delete(Wallet wallet); + void deleteAll(); +} diff --git a/src/main/java/org/programmers/springboot/basic/domain/wallet/service/WalletService.java b/src/main/java/org/programmers/springboot/basic/domain/wallet/service/WalletService.java new file mode 100644 index 0000000000..90db83e716 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/domain/wallet/service/WalletService.java @@ -0,0 +1,134 @@ +package org.programmers.springboot.basic.domain.wallet.service; + +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.dto.CustomerResponseDto; +import org.programmers.springboot.basic.domain.customer.entity.Customer; +import org.programmers.springboot.basic.domain.customer.entity.vo.Email; +import org.programmers.springboot.basic.domain.customer.exception.CustomerNotFoundException; +import org.programmers.springboot.basic.domain.customer.mapper.CustomerMapper; +import org.programmers.springboot.basic.domain.customer.repository.JdbcCustomerRepository; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.Voucher; +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; +import org.programmers.springboot.basic.domain.voucher.mapper.VoucherMapper; +import org.programmers.springboot.basic.domain.voucher.repository.VoucherRepository; +import org.programmers.springboot.basic.domain.wallet.dto.WalletRequestDto; +import org.programmers.springboot.basic.domain.wallet.dto.WalletResponseDto; +import org.programmers.springboot.basic.domain.wallet.entity.Wallet; +import org.programmers.springboot.basic.domain.wallet.exception.DuplicateWalletException; +import org.programmers.springboot.basic.domain.wallet.mapper.WalletMapper; +import org.programmers.springboot.basic.domain.wallet.repository.WalletRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.UUID; + +@Slf4j +@Service +public class WalletService { + + private final WalletRepository walletRepository; + private final VoucherRepository voucherRepository; + private final JdbcCustomerRepository customerRepository; + + @Autowired + public WalletService(WalletRepository walletRepository, VoucherRepository voucherRepository, JdbcCustomerRepository customerRepository) { + this.walletRepository = walletRepository; + this.voucherRepository = voucherRepository; + this.customerRepository = customerRepository; + } + + @Transactional + public void createWallet(WalletRequestDto walletRequestDto) { + + Customer customer = findCustomerByEmail(walletRequestDto); + Voucher voucher = findVoucherById(walletRequestDto); + if (isDuplicate(customer, voucher)) { + log.warn("email {} and voucherId {} is already exists in Wallet", + customer.getEmail().getEmail(), customer.getCustomerId()); + throw new DuplicateWalletException(); + } + + Wallet wallet = WalletMapper.INSTANCE.mapToEntity(walletRequestDto); + this.walletRepository.save(wallet); + } + + private boolean isDuplicate(Customer customer, Voucher voucher) { + return walletRepository.findByEmailNId(customer.getEmail(), voucher.getVoucherId()).isPresent(); + } + + public List walletListByEmail(WalletRequestDto walletRequestDto) { + + Customer customer = findCustomerByEmail(walletRequestDto); + Email email = customer.getEmail(); + + email.validate(); + + List wallets = this.walletRepository.findByEmail(email); + return wallets.stream() + .map(WalletMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + public List voucherListFromWallet(List walletResponseDtos) { + + return walletResponseDtos.stream() + .map(WalletResponseDto::getVoucherId) + .map(voucherRepository::findById) + .map(voucher -> voucher.orElse(null)) + .map(VoucherMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + public List walletListByVoucherId(WalletRequestDto walletRequestDto) { + + Voucher voucher = findVoucherById(walletRequestDto); + UUID voucherId = voucher.getVoucherId(); + List wallets = this.walletRepository.findById(voucherId); + + return wallets.stream() + .map(WalletMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + public List customerListFromWallet(List walletResponseDtos) { + + return walletResponseDtos.stream() + .map(WalletResponseDto::getEmail) + .map(customerRepository::findByEmail) + .map(customer -> customer.orElse(null)) + .map(CustomerMapper.INSTANCE::mapToResponseDto) + .toList(); + } + + public Customer findCustomerByEmail(WalletRequestDto walletRequestDto) { + + Email email = walletRequestDto.getEmail(); + email.validate(); + + return this.customerRepository.findByEmail(email) + .orElseThrow(() -> { + log.warn("No customer found for email: {}", email); + return new CustomerNotFoundException(); + }); + } + + public Voucher findVoucherById(WalletRequestDto walletRequestDto) { + + UUID voucherId = walletRequestDto.getVoucherId(); + return this.voucherRepository.findById(voucherId) + .orElseThrow(() -> { + log.warn("No voucher found for voucherId: {}", voucherId); + return new VoucherNotFoundException(); + }); + } + + @Transactional + public void removeVoucherFromWallet(WalletRequestDto walletRequestDto) { + + Wallet wallet = WalletMapper.INSTANCE.mapToEntity(walletRequestDto); + this.walletRepository.delete(wallet); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/CommandType.java b/src/main/java/org/programmers/springboot/basic/util/CommandType.java new file mode 100644 index 0000000000..18f057be28 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/CommandType.java @@ -0,0 +1,38 @@ +package org.programmers.springboot.basic.util; + +import org.programmers.springboot.basic.util.exception.CommandNotFoundException; + +import java.util.Arrays; + +public enum CommandType { + + VOUCHER, + CUSTOMER, + CREATE, + LIST, + FIND, + UPDATE, + BLACKLIST, + ADD_BLACK, + DELETE_BLACK, + WALLET, + REMOVE, + DELETE, + DELETE_ALL, + ASSIGN, + BACK, + EXIT, + ERROR; + + public static CommandType valueOfCommand(String command) { + + return Arrays.stream(values()) + .filter(value -> value.getLowerCase().equals(command)) + .findAny() + .orElseThrow(CommandNotFoundException::new); + } + + public String getLowerCase() { + return this.name().toLowerCase(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/converter/UUIDConverter.java b/src/main/java/org/programmers/springboot/basic/util/converter/UUIDConverter.java new file mode 100644 index 0000000000..65b62ecef0 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/converter/UUIDConverter.java @@ -0,0 +1,18 @@ +package org.programmers.springboot.basic.util.converter; + +import java.nio.ByteBuffer; +import java.util.UUID; + +public class UUIDConverter { + + private UUIDConverter() {} + + public static UUID toUUID(byte[] bytes) { + ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); + return new UUID(byteBuffer.getLong(), byteBuffer.getLong()); + } + + public static byte[] toBytes(UUID uuid) { + return uuid.toString().getBytes(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/exception/CSVFileIOFailureException.java b/src/main/java/org/programmers/springboot/basic/util/exception/CSVFileIOFailureException.java new file mode 100644 index 0000000000..53b6d5a5dd --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/exception/CSVFileIOFailureException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.util.exception; + +public class CSVFileIOFailureException extends RuntimeException { + + public CSVFileIOFailureException(String msg) { + super(msg); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/exception/CommandNotFoundException.java b/src/main/java/org/programmers/springboot/basic/util/exception/CommandNotFoundException.java new file mode 100644 index 0000000000..d208cdaa45 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/exception/CommandNotFoundException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.util.exception; + +public class CommandNotFoundException extends RuntimeException { + + public CommandNotFoundException() { + super("No matching commands found!"); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/exception/ConsoleIOFailureException.java b/src/main/java/org/programmers/springboot/basic/util/exception/ConsoleIOFailureException.java new file mode 100644 index 0000000000..e446975542 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/exception/ConsoleIOFailureException.java @@ -0,0 +1,13 @@ +package org.programmers.springboot.basic.util.exception; + +public class ConsoleIOFailureException extends RuntimeException { + + public ConsoleIOFailureException(String msg) { + super(msg); + } + + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/generator/DateTimeGenerator.java b/src/main/java/org/programmers/springboot/basic/util/generator/DateTimeGenerator.java new file mode 100644 index 0000000000..0a12bd2c3f --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/generator/DateTimeGenerator.java @@ -0,0 +1,8 @@ +package org.programmers.springboot.basic.util.generator; + +import java.time.LocalDateTime; + +public interface DateTimeGenerator { + + LocalDateTime generateDateTime(); +} diff --git a/src/main/java/org/programmers/springboot/basic/util/generator/NowDateTimeGenerator.java b/src/main/java/org/programmers/springboot/basic/util/generator/NowDateTimeGenerator.java new file mode 100644 index 0000000000..e7178abb02 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/generator/NowDateTimeGenerator.java @@ -0,0 +1,14 @@ +package org.programmers.springboot.basic.util.generator; + +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; + +@Component +public class NowDateTimeGenerator implements DateTimeGenerator { + + @Override + public LocalDateTime generateDateTime() { + return LocalDateTime.now(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/generator/UUIDGenerator.java b/src/main/java/org/programmers/springboot/basic/util/generator/UUIDGenerator.java new file mode 100644 index 0000000000..06dfcef7cc --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/generator/UUIDGenerator.java @@ -0,0 +1,8 @@ +package org.programmers.springboot.basic.util.generator; + +import java.util.UUID; + +public interface UUIDGenerator { + + UUID generateUUID(); +} diff --git a/src/main/java/org/programmers/springboot/basic/util/generator/UUIDRandomGenerator.java b/src/main/java/org/programmers/springboot/basic/util/generator/UUIDRandomGenerator.java new file mode 100644 index 0000000000..6776d89bb2 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/generator/UUIDRandomGenerator.java @@ -0,0 +1,16 @@ +package org.programmers.springboot.basic.util.generator; + +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +@Primary +public class UUIDRandomGenerator implements UUIDGenerator { + + @Override + public UUID generateUUID() { + return UUID.randomUUID(); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/handler/GlobalExceptionHandler.java b/src/main/java/org/programmers/springboot/basic/util/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000000..c6c79e745e --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/handler/GlobalExceptionHandler.java @@ -0,0 +1,84 @@ +package org.programmers.springboot.basic.util.handler; + +import org.programmers.springboot.basic.domain.customer.exception.CustomerNotFoundException; +import org.programmers.springboot.basic.domain.customer.exception.DuplicateBlackCustomerException; +import org.programmers.springboot.basic.domain.customer.exception.DuplicateEmailException; +import org.programmers.springboot.basic.domain.voucher.exception.DuplicateVoucherException; +import org.programmers.springboot.basic.domain.voucher.exception.IllegalDiscountException; +import org.programmers.springboot.basic.domain.voucher.exception.VoucherNotFoundException; +import org.programmers.springboot.basic.domain.wallet.exception.DuplicateWalletException; +import org.programmers.springboot.basic.util.response.ErrCode; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.programmers.springboot.basic.util.response.ErrResponse; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(IllegalArgumentException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException e) { + ErrResponse response = new ErrResponse(ErrCode.BAD_REQUEST, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(NumberFormatException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleNumberFormatException(NumberFormatException e) { + ErrResponse response = new ErrResponse(ErrCode.BAD_REQUEST, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(IllegalDiscountException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleIllegalDiscountException(IllegalDiscountException e) { + ErrResponse response = new ErrResponse(ErrCode.INPUT_INVALID_VALUE, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(DuplicateVoucherException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleDuplicateVoucherException(DuplicateVoucherException e) { + ErrResponse response = new ErrResponse(ErrCode.BAD_REQUEST, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(DuplicateEmailException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleDuplicateEmailException(DuplicateEmailException e) { + ErrResponse response = new ErrResponse(ErrCode.BAD_REQUEST, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(DuplicateBlackCustomerException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleDuplicateBlackCustomerException(DuplicateBlackCustomerException e) { + ErrResponse response = new ErrResponse(ErrCode.BAD_REQUEST, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(DuplicateWalletException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleDuplicateWalletException(DuplicateWalletException e) { + ErrResponse response = new ErrResponse(ErrCode.BAD_REQUEST, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(VoucherNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseEntity handleVoucherNotFoundException(VoucherNotFoundException e) { + ErrResponse response = new ErrResponse(ErrCode.NOT_FOUND, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(CustomerNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseEntity handleCustomerNotFoundException(CustomerNotFoundException e) { + ErrResponse response = new ErrResponse(ErrCode.NOT_FOUND, e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } + +} diff --git a/src/main/java/org/programmers/springboot/basic/util/manager/CommandManager.java b/src/main/java/org/programmers/springboot/basic/util/manager/CommandManager.java new file mode 100644 index 0000000000..9d657feab8 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/manager/CommandManager.java @@ -0,0 +1,144 @@ +package org.programmers.springboot.basic.util.manager; + +import lombok.extern.slf4j.Slf4j; +import org.programmers.springboot.basic.domain.customer.controller.CustomerController; +import org.programmers.springboot.basic.domain.voucher.controller.VoucherController; +import org.programmers.springboot.basic.domain.wallet.controller.WalletController; +import org.programmers.springboot.basic.util.CommandType; +import org.programmers.springboot.basic.util.exception.CommandNotFoundException; +import org.programmers.springboot.basic.util.exception.ConsoleIOFailureException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class CommandManager implements CommandLineRunner { + + private final ConsoleIOManager consoleIOManager; + private final VoucherController voucherController; + private final CustomerController customerController; + private final WalletController walletController; + + @Autowired + public CommandManager(ConsoleIOManager consoleIOManager, VoucherController voucherController, CustomerController customerController, WalletController walletController) { + this.consoleIOManager = consoleIOManager; + this.voucherController = voucherController; + this.customerController = customerController; + this.walletController = walletController; + } + + @Override + public void run(String... args) { + + boolean flag = true; + + try { + while (flag) { + + consoleIOManager.printSystem(); + + String input = consoleIOManager.getInput(); + CommandType command = CommandType.ERROR; + try { + command = CommandType.valueOfCommand(input); + log.info("Command '{}' invoked in voucherManagement Program", command); + } catch (CommandNotFoundException e) { + log.warn(e.toString()); + flag = false; + } + + switch (command) { + + case VOUCHER -> voucherHandler(); + case CUSTOMER -> customerHandler(); + case EXIT -> { + consoleIOManager.printExit(); + flag = false; + } + case ERROR -> consoleIOManager.printErrCommand(); + } + } + } catch (ConsoleIOFailureException e) { + log.error(e.toString()); + } + } + + private void voucherHandler() { + + boolean flag = true; + + try { + while (flag) { + consoleIOManager.printVoucherSystem(); + + String input = consoleIOManager.getInput(); + CommandType command = CommandType.ERROR; + try { + command = CommandType.valueOfCommand(input); + log.info("Command '{}' invoked in voucherHandler", command); + } catch (CommandNotFoundException e) { + log.warn(e.toString()); + } + + switch (command) { + + case CREATE -> voucherController.create(); + case LIST -> voucherController.list(); + case FIND -> voucherController.find(); + case CUSTOMER -> walletController.findCustomerListByVoucherId(); + case UPDATE -> voucherController.update(); + case DELETE -> voucherController.delete(); + case DELETE_ALL -> voucherController.deleteAll(); + case BACK -> { + consoleIOManager.printBackHandler(); + flag = false; + } + default -> consoleIOManager.printErrCommand(); + } + } + } catch (ConsoleIOFailureException e) { + log.error(e.toString()); + } + } + + private void customerHandler() { + + boolean flag = true; + + try { + while (flag) { + consoleIOManager.printCustomerSystem(); + + String input = consoleIOManager.getInput(); + CommandType command = CommandType.ERROR; + try { + command = CommandType.valueOfCommand(input); + } catch (CommandNotFoundException e) { + log.warn(e.toString()); + } + + switch (command) { + + case CREATE -> customerController.create(); + case LIST -> customerController.list(); + case BLACKLIST -> customerController.blacklist(); + case ASSIGN -> walletController.addWallet(); + case WALLET -> walletController.findVoucherListByEmail(); + case REMOVE -> walletController.removeVoucherFromWallet(); + case DELETE -> customerController.delete(); + case ADD_BLACK -> customerController.addToBlackList(); + case DELETE_BLACK -> customerController.deleteFromBlackList(); + case DELETE_ALL -> customerController.deleteAll(); + case BACK -> { + consoleIOManager.printBackHandler(); + flag = false; + } + default -> consoleIOManager.printErrCommand(); + } + } + } catch (ConsoleIOFailureException e) { + log.error(e.toString()); + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/manager/ConsoleIOManager.java b/src/main/java/org/programmers/springboot/basic/util/manager/ConsoleIOManager.java new file mode 100644 index 0000000000..64702fd472 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/manager/ConsoleIOManager.java @@ -0,0 +1,328 @@ +package org.programmers.springboot.basic.util.manager; + +import org.programmers.springboot.basic.domain.customer.dto.CustomerResponseDto; +import org.programmers.springboot.basic.domain.customer.entity.Customer; +import org.programmers.springboot.basic.domain.voucher.dto.VoucherResponseDto; +import org.programmers.springboot.basic.domain.voucher.entity.Voucher; +import org.programmers.springboot.basic.util.exception.ConsoleIOFailureException; +import org.springframework.stereotype.Component; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.List; + +@Component +public class ConsoleIOManager { + + public BufferedReader getBufferedReader() { + return new BufferedReader(new InputStreamReader(System.in)); + } + + public String getInput() { + try { + return getBufferedReader().readLine(); + } catch (IOException e) { + throw new ConsoleIOFailureException("[System] 콘솔에 입력된 값을 받아오는데 실패했습니다.\n"); + } + } + + public int getInteger() { + return Integer.parseInt(getInput()); + } + + public Long getLong() { + return Long.parseLong(getInput()); + } + + public void printSystem() { + + String msg = """ + === Voucher Management Program === + Type exit to exit the program. + Type voucher to enter a voucher program. + Type customer to enter a customer program. + """; + System.out.println(msg); + } + + public void printVoucherSystem() { + + String msg = """ + === Voucher Program === + Type create to a new voucher. + Type list to list all voucher. + Type find to find a voucher by voucherId. + Type customer to list all customer by voucherId. + Type update to update voucher. + Type delete to delete a voucher by voucherId. + Type delete_all to delete all voucher. + Type back to back voucherManagement program. + """; + System.out.println(msg); + } + + public void printCustomerSystem() { + + String msg = """ + === Customer Program === + Type create to a new customer. + Type list to list all customer. + Type blacklist to list all blacklist. + Type assign to add voucher in wallet by email and voucherId. + Type wallet to list all voucher by email. + Type remove to remove voucher from wallet by voucherId. + Type delete to delete voucher. + Type add_black to add customer to blacklist. + Type delete_black to delete customer from blacklist. + Type delete_all to delete all customer. + Type back to back voucherManagement program + """; + System.out.println(msg); + } + + public void printVoucherCreateHandler() { + + String msg = """ + === CREATE === + 1. FixedAmountVoucher + 2. PercentAmountVoucher + + Q. Enter type of NUMBER you want to create: + """; + System.out.println(msg); + } + + public void printFoundVoucher(VoucherResponseDto voucherResponseDto) { + + String msg = """ + === LIST === + """; + System.out.println(msg); + printVoucherInfo(voucherResponseDto); + } + + public void printCustomerCreateHandler() { + + String msg = """ + === CREATE === + Q. Enter name type of STRING you want to create: + Q. Enter email type of STRING you want to create: + """; + System.out.println(msg); + } + + public void printFindHandler() { + + String msg = """ + === FIND === + Q. Enter voucherId type of UUID you want to find: + """; + System.out.println(msg); + } + + public void printUpdateHandler() { + + String msg = """ + === UPDATE === + Q. Enter voucherId type of UUID you want to update: + Q. Enter discount type of NUMBER you want to update: + """; + System.out.println(msg); + } + + public void printVoucherDeleteHandler() { + + String msg = """ + === DELETE === + Q. Enter voucherId type of UUID you want to delete: + """; + System.out.println(msg); + } + + public void printCustomerDeleteHandler() { + + String msg = """ + === DELETE === + Q. Enter customerId type of UUID you want to delete: + """; + System.out.println(msg); + } + + public void printDeleteAllHandler() { + String msg = """ + === DELETE ALL === + Q, Enter Y if you really want to delete all info (or not: any else) + """; + System.out.println(msg); + } + + public void printAddBlackHandler() { + + String msg = """ + === ADD BLACKLIST === + Q. Enter customerId type of UUID you want to add blacklist: + """; + System.out.println(msg); + } + + public void printDeleteBlackHandler() { + + String msg = """ + === DELETE BLACKLIST === + Q. Enter customerId type of UUID you want to delete from blacklist: + """; + System.out.println(msg); + } + + public void printListByConsumerHandler() { + + String msg = """ + === Voucher LIST ABOUT Email === + Q. Enter email type of STRING you want to list vouchers owned by the customer: + """; + System.out.println(msg); + } + + public void printListByVoucherHandler() { + + String msg = """ + === Customer LIST ABOUT VoucherId === + Q. Enter voucherId type of UUID you want to list customers grouped by the voucher: + """; + System.out.println(msg); + } + + public void printRemoveVoucherFromWalletHandler() { + + String msg = """ + === REMOVE VOUCHER FROM WALLET === + Q. Enter email and voucherId (type of UUID) you want to remove voucher from wallet: + """; + System.out.println(msg); + } + + public void printAssignHandler() { + + String msg = """ + === ASSIGN === + Q. Enter email type of STRING you want to assign: + Q. Enter voucherId type of UUID you want to assign from wallet: + """; + System.out.println(msg); + } + + public void printVoucher(List responseDtos) { + String msg = """ + === Voucher List === + """; + System.out.println(msg); + responseDtos.forEach(this::printVoucherInfo); + } + + public void printCustomer(List responseDtos) { + String msg = """ + === Customer List === + """; + System.out.println(msg); + responseDtos.forEach(this::printCustomerInfo); + } + + public void printBlackList(List responseDtos) { + String msg = """ + === BlackList === + """; + System.out.println(msg); + responseDtos.forEach(this::printBlackListInfo); + } + + public void printVoucherInfo(VoucherResponseDto responseDto) { + + String msg = String.format(""" + voucherId: %s + voucherType: %s + discount: %d%% + --------------------------------- + """, responseDto.getVoucherId().toString(), responseDto.getVoucherType(), responseDto.getDiscount()); + System.out.println(msg); + } + + public void printCustomerInfo(CustomerResponseDto responseDto) { + + String msg = String.format(""" + customerId: %s + email: %s + name: %s + customerType: %s + --------------------------------- + """, responseDto.getCustomerId().toString(), responseDto.getEmail(), responseDto.getName(), responseDto.getCustomerType()); + System.out.println(msg); + } + + public void printBlackListInfo(CustomerResponseDto responseDto) { + + String msg = String.format(""" + customerId: %s + email: %s + name: %s + --------------------------------- + """, responseDto.getCustomerId().toString(), responseDto.getEmail(), responseDto.getName()); + System.out.println(msg); + } + + public void printWalletInfoByConsumer(Customer customer, List responseDtos) { + + String msg = String.format(""" + === customer Info === + customerId: %s + email: %s + name: %s + customerType: %s + ========================================== + """, customer.getCustomerId().toString(), customer.getEmail(), customer.getName(), customer.getCustomerType()); + System.out.println(msg); + printVoucher(responseDtos); + } + + public void printWalletInfoByVoucher(Voucher voucher, List responseDtos) { + + String msg = String.format(""" + === voucher Info === + voucherId: %s + voucherType: %s + discount: %d%% + ========================================== + """, voucher.getVoucherId().toString(), voucher.getVoucherType(), voucher.getDiscount()); + System.out.println(msg); + printCustomer(responseDtos); + } + + public void printBackHandler() { + + String msg = """ + [System] VoucherManagement 메뉴로 돌아갑니다. + """; + System.out.println(msg); + } + + public void printRequestDiscount() { + String msg = """ + Q. Enter discount type of NUMBER you want to create. + """; + System.out.println(msg); + } + + public void printExit() { + String msg = """ + [System] 시스템을 종료합니다. + """; + System.out.println(msg); + } + + public void printErrCommand() { + String msg = """ + [System] 잘못된 명령의 접근입니다. + """; + System.out.println(msg); + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/properties/ExternalProperties.java b/src/main/java/org/programmers/springboot/basic/util/properties/ExternalProperties.java new file mode 100644 index 0000000000..d6eb5c75d7 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/properties/ExternalProperties.java @@ -0,0 +1,28 @@ +package org.programmers.springboot.basic.util.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "external") +public class ExternalProperties { + + private String projDir; + private String resourceDir; + + public String getProjDir() { + return projDir; + } + + public void setProjDir(String projDir) { + this.projDir = projDir; + } + + public String getResourceDir() { + return resourceDir; + } + + public void setResourceDir(String resourceDir) { + this.resourceDir = resourceDir; + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/properties/FileProperties.java b/src/main/java/org/programmers/springboot/basic/util/properties/FileProperties.java new file mode 100644 index 0000000000..f4ece01844 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/properties/FileProperties.java @@ -0,0 +1,80 @@ +package org.programmers.springboot.basic.util.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +@ConfigurationProperties(prefix = "file") +public class FileProperties { + + private final Map names = new HashMap<>(); + private Resources resources; + private String userDir; + + + public Map getNames() { + return names; + } + + public Resources getResources() { + return resources; + } + + public void setResources(Resources resources) { + this.resources = resources; + } + + public String getUserDir() { + return userDir; + } + + public void setUserDir(String userDir) { + this.userDir = userDir; + } + + public static class PathProperties { + + private String fileName; + private String testFileName; + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getTestFileName() { + return testFileName; + } + + public void setTestFileName(String testFileName) { + this.testFileName = testFileName; + } + } + + public static class Resources { + private String path; + private String testPath; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getTestPath() { + return testPath; + } + + public void setTestPath(String testPath) { + this.testPath = testPath; + } + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/response/ErrCode.java b/src/main/java/org/programmers/springboot/basic/util/response/ErrCode.java new file mode 100644 index 0000000000..806148454b --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/response/ErrCode.java @@ -0,0 +1,25 @@ +package org.programmers.springboot.basic.util.response; + +public enum ErrCode { + + NOT_FOUND(404, "존재하지 않는 리소스"), + BAD_REQUEST(400, "유효하지 않은 타입"), + INPUT_INVALID_VALUE(401, "유효하지 않은 범위"), + INTERNAL_SERVER_ERROR(500, "서버 오류"); + + private final int status; + private final String message; + + ErrCode(int status, String message) { + this.status = status; + this.message = message; + } + + public int getStatus() { + return status; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/org/programmers/springboot/basic/util/response/ErrResponse.java b/src/main/java/org/programmers/springboot/basic/util/response/ErrResponse.java new file mode 100644 index 0000000000..6e02908697 --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/util/response/ErrResponse.java @@ -0,0 +1,15 @@ +package org.programmers.springboot.basic.util.response; + +import lombok.Getter; + +@Getter +public class ErrResponse { + + private final ErrCode code; + private final String message; + + public ErrResponse(ErrCode code, String message) { + this.code = code; + this.message = message; + } +} diff --git a/src/main/java/org/programmers/springboot/basic/web/ApplicationController.java b/src/main/java/org/programmers/springboot/basic/web/ApplicationController.java new file mode 100644 index 0000000000..52a79e0bcf --- /dev/null +++ b/src/main/java/org/programmers/springboot/basic/web/ApplicationController.java @@ -0,0 +1,15 @@ +package org.programmers.springboot.basic.web; + +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Profile("default") +@Controller +public class ApplicationController { + + @GetMapping + public String home() { + return "home"; + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000000..b92ff6ac5c --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,10 @@ +spring: + profiles: + active: default + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/voucherManagement?serverTimeZone=Asia/Seoul + username: user + password: user1234 + thymeleaf: + prefix: classpath:/templates/ diff --git a/src/main/resources/customer_blacklist.csv b/src/main/resources/customer_blacklist.csv new file mode 100644 index 0000000000..47a2fdd88e --- /dev/null +++ b/src/main/resources/customer_blacklist.csv @@ -0,0 +1,5 @@ +94401b49-c776-48ba-87da-239719e7a728,마리오,BLACK +d7d3ddd8-9eb4-4cfa-9b6a-788fc4297f3e,와리오,BLACK +86a5b3ba-8a47-475e-9111-3b3f1bf41a71,피치,BLACK +599504e1-84ee-4c7b-b524-007e699b153e,루이지,BLACK +75ad9183-dd31-49e7-a82e-d089af728765,키노피오,BLACK diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000000..e6c290ac73 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,56 @@ + + + + + + + + + INFO + ACCEPT + DENY + + + ${CONSOLE_LOG} + + + + + + WARN + ACCEPT + DENY + + + ${CONSOLE_LOG} + + + + + + ERROR + ACCEPT + DENY + + + ${CONSOLE_LOG} + + + + + + + + + + diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html new file mode 100644 index 0000000000..807a657d46 --- /dev/null +++ b/src/main/resources/templates/error.html @@ -0,0 +1,20 @@ + + + + + Error Occurred + + + +
+

Error Occurred!

+

+
+ +
+ +
+ + + + diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html new file mode 100644 index 0000000000..5c18b8e0fa --- /dev/null +++ b/src/main/resources/templates/home.html @@ -0,0 +1,55 @@ + + + + + + VoucherManagement + + + +
+

VoucherManagement

+
+
+

About Voucher

+ +
+
+
+

About Wallet

+ +
+
+ + + + diff --git a/src/main/resources/templates/voucher/createForm.html b/src/main/resources/templates/voucher/createForm.html new file mode 100644 index 0000000000..6327a4539a --- /dev/null +++ b/src/main/resources/templates/voucher/createForm.html @@ -0,0 +1,36 @@ + + + + + + Create Voucher + + + +
+

Voucher Type:

+
+ 1. FixedMount
+ 2. PercentDiscount

+
+ +
+
+ + +
+
+ + +
+ +
+ +
+ +
+
+ + + + diff --git a/src/main/resources/templates/voucher/deleteForm.html b/src/main/resources/templates/voucher/deleteForm.html new file mode 100644 index 0000000000..7ea45b256f --- /dev/null +++ b/src/main/resources/templates/voucher/deleteForm.html @@ -0,0 +1,25 @@ + + + + + + + Delete Voucher + + + +
+
+ + +
+ +
+ +
+ +
+ + + + diff --git a/src/main/resources/templates/voucher/find.html b/src/main/resources/templates/voucher/find.html new file mode 100644 index 0000000000..6ec81bf317 --- /dev/null +++ b/src/main/resources/templates/voucher/find.html @@ -0,0 +1,39 @@ + + + + + + Voucher Information + + + + +
+

Voucher Information

+ + + + + + + + + + + + + + + + + +
Voucher IDVoucher TypeDiscountCustomer Email
+
+
+
+ +
+
+ + + diff --git a/src/main/resources/templates/voucher/findForm.html b/src/main/resources/templates/voucher/findForm.html new file mode 100644 index 0000000000..faca8e835b --- /dev/null +++ b/src/main/resources/templates/voucher/findForm.html @@ -0,0 +1,24 @@ + + + + + Find Voucher + + + + +
+
+ + +
+ +
+ +
+ +
+ + + + diff --git a/src/main/resources/templates/voucher/updateForm.html b/src/main/resources/templates/voucher/updateForm.html new file mode 100644 index 0000000000..1888cd59f7 --- /dev/null +++ b/src/main/resources/templates/voucher/updateForm.html @@ -0,0 +1,28 @@ + + + + + Update Voucher + + + + +
+
+ + +
+
+ + +
+ +
+ +
+ +
+ + + + diff --git a/src/main/resources/templates/voucher/voucherList.html b/src/main/resources/templates/voucher/voucherList.html new file mode 100644 index 0000000000..49c0495b2f --- /dev/null +++ b/src/main/resources/templates/voucher/voucherList.html @@ -0,0 +1,39 @@ + + + + + + Voucher Information + + + + +
+

Voucher List

+ + + + + + + + + + + + + + + + + +
Voucher IDVoucher TypeDiscountCustomer Email
+
+
+
+ +
+
+ + + diff --git a/src/main/resources/templates/wallet/addForm.html b/src/main/resources/templates/wallet/addForm.html new file mode 100644 index 0000000000..bc161515eb --- /dev/null +++ b/src/main/resources/templates/wallet/addForm.html @@ -0,0 +1,51 @@ + + + + + Add Voucher to Wallet + + + + +

Add Voucher to Wallet

+
+

Voucher List

+ + + + + + + + + + + + + + + + + +
IDTypeDiscountCreated At
+
+
+
+ + +
+
+ + +
+ +
+ +
+ +
+
+ + + + diff --git a/src/main/resources/templates/wallet/customerListInWallet.html b/src/main/resources/templates/wallet/customerListInWallet.html new file mode 100644 index 0000000000..459583b36b --- /dev/null +++ b/src/main/resources/templates/wallet/customerListInWallet.html @@ -0,0 +1,58 @@ + + + + + Customer List + + + +
+

Voucher Information

+ + + + + + + + + + + + + + + + + +
Voucher IDVoucher TypeDiscountCreated At
+
+
+
+
+

Customer List

+ + + + + + + + + + + + + + + + + +
Customer IDNameEmailCustomerType
+
+ +
+ +
+ + diff --git a/src/main/resources/templates/wallet/deleteForm.html b/src/main/resources/templates/wallet/deleteForm.html new file mode 100644 index 0000000000..18caff5bd5 --- /dev/null +++ b/src/main/resources/templates/wallet/deleteForm.html @@ -0,0 +1,30 @@ + + + + + Remove Voucher from Wallet + + + +

Remove Voucher from Wallet

+
+
+
+ + +
+
+ + +
+ +
+ +
+ +
+
+ + + + diff --git a/src/main/resources/templates/wallet/findCustomerForm.html b/src/main/resources/templates/wallet/findCustomerForm.html new file mode 100644 index 0000000000..a489c2a3fd --- /dev/null +++ b/src/main/resources/templates/wallet/findCustomerForm.html @@ -0,0 +1,27 @@ + + + + + Find All Customer From Voucher + + + +
+

Find Vouchers By VoucherId

+
+
+
+ + +
+ +
+ +
+ +
+
+ + + + diff --git a/src/main/resources/templates/wallet/findVoucherForm.html b/src/main/resources/templates/wallet/findVoucherForm.html new file mode 100644 index 0000000000..3643a3f8e3 --- /dev/null +++ b/src/main/resources/templates/wallet/findVoucherForm.html @@ -0,0 +1,27 @@ + + + + + Find All Voucher In Wallet + + + +
+

Find Customers By Email

+
+
+
+ + +
+ +
+ +
+ +
+
+ + + + diff --git a/src/main/resources/templates/wallet/voucherListInWallet.html b/src/main/resources/templates/wallet/voucherListInWallet.html new file mode 100644 index 0000000000..0a472a64bc --- /dev/null +++ b/src/main/resources/templates/wallet/voucherListInWallet.html @@ -0,0 +1,60 @@ + + + + + Voucher List + + + +
+

Customer Information

+ + + + + + + + + + + + + + + + + +
Customer IDNameEmailCustomerType
+
+
+
+
+

Voucher List

+ + + + + + + + + + + + + + + + + +
Voucher IdVoucher TypeDiscountCreated At
+
+ +
+ +
+ + + + diff --git a/src/main/resources/voucherRecord.csv b/src/main/resources/voucherRecord.csv new file mode 100644 index 0000000000..e578a28049 --- /dev/null +++ b/src/main/resources/voucherRecord.csv @@ -0,0 +1,2 @@ +27fce720-8943-444b-8c69-20ea7497a2f6,FIXED,1500 +6aeebac4-1d47-4989-a1e4-5d58091b798a,PERCENT,50 diff --git a/src/test/resources/application-test.properties b/src/test/resources/application-test.properties new file mode 100644 index 0000000000..677ab0d6cb --- /dev/null +++ b/src/test/resources/application-test.properties @@ -0,0 +1,4 @@ +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.datasource.url=jdbc:mysql://localhost:3306/voucherManagement?serverTimeZone=Asia/Seoul +spring.datasource.username=user +spring.datasource.password=user1234 diff --git a/src/test/resources/testVoucherRecord.csv b/src/test/resources/testVoucherRecord.csv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/test/resources/test_customer_blacklist.csv b/src/test/resources/test_customer_blacklist.csv new file mode 100644 index 0000000000..47a2fdd88e --- /dev/null +++ b/src/test/resources/test_customer_blacklist.csv @@ -0,0 +1,5 @@ +94401b49-c776-48ba-87da-239719e7a728,마리오,BLACK +d7d3ddd8-9eb4-4cfa-9b6a-788fc4297f3e,와리오,BLACK +86a5b3ba-8a47-475e-9111-3b3f1bf41a71,피치,BLACK +599504e1-84ee-4c7b-b524-007e699b153e,루이지,BLACK +75ad9183-dd31-49e7-a82e-d089af728765,키노피오,BLACK