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..997b13c0fb --- /dev/null +++ b/build.gradle @@ -0,0 +1,29 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.0' + id 'io.spring.dependency-management' version '1.1.0' +} + +group = 'com.programmers' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + // Lombok + compileOnly 'org.projectlombok:lombok:1.18.26' + annotationProcessor 'org.projectlombok:lombok:1.18.26' + + implementation 'org.springframework.boot:spring-boot-starter' + 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..249e5832f0 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..774fae8767 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000..a69d9cb6c2 --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# 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..f127cfd49d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@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=. +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..2f01e7d093 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'voucher-management' diff --git a/src/main/java/com/programmers/vouchermanagement/CommandLineController.java b/src/main/java/com/programmers/vouchermanagement/CommandLineController.java new file mode 100644 index 0000000000..f9f19d2617 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/CommandLineController.java @@ -0,0 +1,54 @@ +package com.programmers.vouchermanagement; + +import com.programmers.vouchermanagement.view.Command; +import com.programmers.vouchermanagement.view.Console; +import com.programmers.vouchermanagement.voucher.domain.DiscountType; +import com.programmers.vouchermanagement.voucher.dto.VoucherDto; +import com.programmers.vouchermanagement.voucher.presentation.VoucherController; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Controller; + +@Slf4j +@Controller +@RequiredArgsConstructor +public class CommandLineController implements CommandLineRunner { + + private final VoucherController voucherController; + + @Override + public void run(String... args) { + boolean running = true; + + while (running) { + try { + running = isRunning(); + } catch (RuntimeException e) { + Console.outputErrorMessage(e.getMessage()); + log.error(e.getMessage()); + } + + } + } + + private boolean isRunning() { + Command command = Command.from(Console.selectCommand()); + switch (command) { + case CREATE -> { + DiscountType discountType = DiscountType.from(Console.selectDiscountType()); + int discountAmount = Console.inputDiscountAmount(); + VoucherDto.Request request = new VoucherDto.Request(discountType, discountAmount); + voucherController.createVoucher(request); + } + case LIST-> { + VoucherDto.Response vouchers = voucherController.getVouchers(); + Console.outputVouchers(vouchers); + } + case EXIT -> { + return false; + } + } + return true; + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/VoucherManagementApplication.java b/src/main/java/com/programmers/vouchermanagement/VoucherManagementApplication.java new file mode 100644 index 0000000000..df8683ebea --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/VoucherManagementApplication.java @@ -0,0 +1,13 @@ +package com.programmers.vouchermanagement; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VoucherManagementApplication { + + public static void main(String[] args) { + SpringApplication.run(VoucherManagementApplication.class, args); + } + +} diff --git a/src/main/java/com/programmers/vouchermanagement/docs/README.md b/src/main/java/com/programmers/vouchermanagement/docs/README.md new file mode 100644 index 0000000000..8a52f73d7f --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/docs/README.md @@ -0,0 +1,21 @@ +# 기능 명세서 +>바우처 관리 Command-line Application을 만들기 + +## Domain +### 바우처 +```markdown +- 바우처마다 할인 정책이 다르기 때문에 바우처를 인터페이스로 구현 + - 정액 할인 바우처 + - 정률 할인 바우처 +- 값을 할인한다. +- 바우처 저장소 변경에 유연한 대처를 위해 인터페이스로 구현 + - 메모리 바우처 저장소 (개발 환경에서 동작) + - 파일 바우처 저장소 +- 바우처를 저장한다. +- 바우처를 조회한다. +``` + +### 고객 +```markdown +- 고객 블랙 리스트 명단을 조회한다. +``` \ No newline at end of file diff --git a/src/main/java/com/programmers/vouchermanagement/view/Command.java b/src/main/java/com/programmers/vouchermanagement/view/Command.java new file mode 100644 index 0000000000..6d80749e53 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/view/Command.java @@ -0,0 +1,37 @@ +package com.programmers.vouchermanagement.view; + +import java.util.Collections; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public enum Command { + + CREATE("create"), + LIST("list"), + EXIT("exit"); + + private final String name; + private static final Map COMMAND_MAP; + + static { + COMMAND_MAP = Collections.unmodifiableMap(Stream.of(values()) + .collect(Collectors.toMap(Command::getName, Function.identity()))); + } + + Command(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public static Command from(String name) { + if (COMMAND_MAP.containsKey(name)) { + return COMMAND_MAP.get(name); + } + throw new IllegalArgumentException("This command does not exist."); + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/view/Console.java b/src/main/java/com/programmers/vouchermanagement/view/Console.java new file mode 100644 index 0000000000..a0e1a21fb5 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/view/Console.java @@ -0,0 +1,62 @@ +package com.programmers.vouchermanagement.view; + +import com.programmers.vouchermanagement.voucher.dto.VoucherDto; + +import java.util.Scanner; +import java.util.stream.Collectors; + +public class Console { + + private final static Scanner SCANNER = new Scanner(System.in); + + private static String inputString() { + return SCANNER.nextLine(); + } + + public static String selectCommand() { + System.out.println(""" + + === Voucher Program === + Type exit to exit the program. + Type create to create a new voucher. + Type list to list all vouchers. + """); + return inputString(); + } + + public static String selectDiscountType() { + System.out.println(""" + + Choose a discount type. + Type fix to select a fixed discount + Type percent to select a fixed discount + """); + return inputString(); + } + + public static int inputDiscountAmount() { + System.out.println("\nPlease enter the discount amount\n"); + return inputInt(); + } + + private static int inputInt() { + int inputValue = 0; + try { + inputValue = Integer.parseInt(inputString()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Please enter only numbers."); + } + return inputValue; + } + + public static void outputVouchers(VoucherDto.Response vouchers) { + System.out.println("\nThis is a list of vouchers"); + System.out.println(vouchers.voucherName().stream() + .map(voucher -> voucher + System.lineSeparator()) + .collect(Collectors.joining())); + } + + public static void outputErrorMessage(String errorMessage) { + System.out.println(errorMessage); + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/application/VoucherFactory.java b/src/main/java/com/programmers/vouchermanagement/voucher/application/VoucherFactory.java new file mode 100644 index 0000000000..f83bc1ac02 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/application/VoucherFactory.java @@ -0,0 +1,16 @@ +package com.programmers.vouchermanagement.voucher.application; + +import com.programmers.vouchermanagement.voucher.domain.DiscountType; +import com.programmers.vouchermanagement.voucher.domain.FixedAmountVoucher; +import com.programmers.vouchermanagement.voucher.domain.PercentDiscountVoucher; +import com.programmers.vouchermanagement.voucher.domain.Voucher; + +public class VoucherFactory { + + public static Voucher createVoucher(DiscountType discountType, int discountAmount) { + if (discountType == DiscountType.FIX) { + return new FixedAmountVoucher(discountAmount); + } + return new PercentDiscountVoucher(discountAmount); + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/application/VoucherService.java b/src/main/java/com/programmers/vouchermanagement/voucher/application/VoucherService.java new file mode 100644 index 0000000000..f27d10b8c0 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/application/VoucherService.java @@ -0,0 +1,29 @@ +package com.programmers.vouchermanagement.voucher.application; + +import com.programmers.vouchermanagement.voucher.domain.Voucher; +import com.programmers.vouchermanagement.voucher.domain.VoucherRepository; +import com.programmers.vouchermanagement.voucher.dto.VoucherDto; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Slf4j +@Service +@RequiredArgsConstructor +public class VoucherService { + + private final VoucherRepository voucherRepository; + + public void createVoucher(VoucherDto.Request request) { + Voucher voucher = VoucherFactory.createVoucher(request.discountType(), request.discountAmount()); + voucherRepository.save(voucher); + log.info("Create Voucher! DiscountType: {}, DiscountAmount: {}", voucher.getClass().getSimpleName(), request.discountAmount()); + } + + public VoucherDto.Response getVouchers() { + List vouchers = voucherRepository.findAll(); + return VoucherDto.Response.toDto(vouchers); + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/domain/DiscountType.java b/src/main/java/com/programmers/vouchermanagement/voucher/domain/DiscountType.java new file mode 100644 index 0000000000..43a7ed1426 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/domain/DiscountType.java @@ -0,0 +1,36 @@ +package com.programmers.vouchermanagement.voucher.domain; + +import java.util.Collections; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public enum DiscountType { + + FIX("fix"), + PERCENT("percent"); + + private final String name; + private static final Map DISCOUNT_TYPE_MAP; + + static { + DISCOUNT_TYPE_MAP = Collections.unmodifiableMap(Stream.of(values()) + .collect(Collectors.toMap(DiscountType::getName, Function.identity()))); + } + + DiscountType(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public static DiscountType from(String name) { + if (DISCOUNT_TYPE_MAP.containsKey(name)) { + return DISCOUNT_TYPE_MAP.get(name); + } + throw new IllegalArgumentException("This discount type does not exist."); + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/domain/FixedAmountVoucher.java b/src/main/java/com/programmers/vouchermanagement/voucher/domain/FixedAmountVoucher.java new file mode 100644 index 0000000000..4d5fdb52fa --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/domain/FixedAmountVoucher.java @@ -0,0 +1,36 @@ +package com.programmers.vouchermanagement.voucher.domain; + +import java.util.UUID; + +public class FixedAmountVoucher implements Voucher { + + public static final int MIN_AMOUNT = 1; + + private final UUID id; + private final int amount; + + public FixedAmountVoucher(int amount) { + validationAmount(amount); + this.id = UUID.randomUUID(); + this.amount = amount; + } + + private void validationAmount(int amount) { + if (amount <= MIN_AMOUNT) { + throw new IllegalArgumentException("The minimum discount amount is 1."); + } + } + + @Override + public UUID getId() { + return this.id; + } + + @Override + public int discount(int originalPrice) { + if (amount > originalPrice) { + return 0; + } + return originalPrice - amount; + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/domain/PercentDiscountVoucher.java b/src/main/java/com/programmers/vouchermanagement/voucher/domain/PercentDiscountVoucher.java new file mode 100644 index 0000000000..8c348dc9ca --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/domain/PercentDiscountVoucher.java @@ -0,0 +1,34 @@ +package com.programmers.vouchermanagement.voucher.domain; + +import java.util.UUID; + +public class PercentDiscountVoucher implements Voucher { + + public static final int MIN_PERCENT = 1; + public static final int MAX_PERCENT = 100; + + private final UUID id; + private final int amount; + + public PercentDiscountVoucher(int amount) { + validationAmount(amount); + this.id = UUID.randomUUID(); + this.amount = amount; + } + + private void validationAmount(int amount) { + if (MIN_PERCENT > amount || amount > MAX_PERCENT) { + throw new IllegalArgumentException("The discount percentage must be between 1 and 100%."); + } + } + + @Override + public UUID getId() { + return this.id; + } + + @Override + public int discount(int originalPrice) { + return originalPrice * (amount / MAX_PERCENT); + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/domain/Voucher.java b/src/main/java/com/programmers/vouchermanagement/voucher/domain/Voucher.java new file mode 100644 index 0000000000..fd955ae5b4 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/domain/Voucher.java @@ -0,0 +1,10 @@ +package com.programmers.vouchermanagement.voucher.domain; + +import java.util.UUID; + +public interface Voucher { + + UUID getId(); + + int discount(int originalPrice); +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/domain/VoucherRepository.java b/src/main/java/com/programmers/vouchermanagement/voucher/domain/VoucherRepository.java new file mode 100644 index 0000000000..d2f385ca65 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/domain/VoucherRepository.java @@ -0,0 +1,10 @@ +package com.programmers.vouchermanagement.voucher.domain; + +import java.util.List; + +public interface VoucherRepository { + + Voucher save(Voucher voucher); + + List findAll(); +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/dto/VoucherDto.java b/src/main/java/com/programmers/vouchermanagement/voucher/dto/VoucherDto.java new file mode 100644 index 0000000000..0e20dd578c --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/dto/VoucherDto.java @@ -0,0 +1,29 @@ +package com.programmers.vouchermanagement.voucher.dto; + +import com.programmers.vouchermanagement.voucher.domain.DiscountType; +import com.programmers.vouchermanagement.voucher.domain.Voucher; + +import java.util.List; +import java.util.stream.Collectors; + +public class VoucherDto { + + public record Request(DiscountType discountType, int discountAmount) { + } + + public record Response(List voucherName) { + + @Override + public List voucherName() { + return voucherName; + } + + public static VoucherDto.Response toDto(List vouchers) { + List vourcherList = vouchers.stream() + .map(voucher -> voucher.getClass().getSimpleName()) + .collect(Collectors.toList()); + return new VoucherDto.Response(vourcherList); + } + } + +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/infrastructure/MemoryVoucherRepository.java b/src/main/java/com/programmers/vouchermanagement/voucher/infrastructure/MemoryVoucherRepository.java new file mode 100644 index 0000000000..41bd15da65 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/infrastructure/MemoryVoucherRepository.java @@ -0,0 +1,28 @@ +package com.programmers.vouchermanagement.voucher.infrastructure; + +import com.programmers.vouchermanagement.voucher.domain.Voucher; +import com.programmers.vouchermanagement.voucher.domain.VoucherRepository; +import org.springframework.stereotype.Repository; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +@Repository +public class MemoryVoucherRepository implements VoucherRepository { + + private static final Map storage = new ConcurrentHashMap<>(); + + @Override + public Voucher save(Voucher voucher) { + storage.put(voucher.getId(), voucher); + return voucher; + } + + @Override + public List findAll() { + return new ArrayList<>(storage.values()); + } +} diff --git a/src/main/java/com/programmers/vouchermanagement/voucher/presentation/VoucherController.java b/src/main/java/com/programmers/vouchermanagement/voucher/presentation/VoucherController.java new file mode 100644 index 0000000000..41d0733eb9 --- /dev/null +++ b/src/main/java/com/programmers/vouchermanagement/voucher/presentation/VoucherController.java @@ -0,0 +1,21 @@ +package com.programmers.vouchermanagement.voucher.presentation; + +import com.programmers.vouchermanagement.voucher.application.VoucherService; +import com.programmers.vouchermanagement.voucher.dto.VoucherDto; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; + +@Controller +@RequiredArgsConstructor +public class VoucherController { + + private final VoucherService voucherService; + + public void createVoucher(VoucherDto.Request request) { + voucherService.createVoucher(request); + } + + public VoucherDto.Response getVouchers() { + return voucherService.getVouchers(); + } +} diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000000..168e7ebf0d --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,31 @@ + + + + + + + + + ${LOG_PATTERN} + + + + + logs/${byDay}.log + + ${LOG_PATTERN} + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/java/com/programmers/vouchermanagement/VoucherManagementApplicationTests.java b/src/test/java/com/programmers/vouchermanagement/VoucherManagementApplicationTests.java new file mode 100644 index 0000000000..85414204ad --- /dev/null +++ b/src/test/java/com/programmers/vouchermanagement/VoucherManagementApplicationTests.java @@ -0,0 +1,13 @@ +package com.programmers.vouchermanagement; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class VoucherManagementApplicationTests { + + @Test + void contextLoads() { + } + +}