diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..318f7069 --- /dev/null +++ b/.gitignore @@ -0,0 +1,322 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij+all,gradle,java,maven,linux,windows,macos,vim,eclipse +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all,gradle,java,maven,linux,windows,macos,vim,eclipse + +### Eclipse ### +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath +.recommenders + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# PyDev specific (Python IDE for Eclipse) +*.pydevproject + +# CDT-specific (C/C++ Development Tooling) +.cproject + +# CDT- autotools +.autotools + +# Java annotation processor (APT) +.factorypath + +# PDT-specific (PHP Development Tools) +.buildpath + +# sbteclipse plugin +.target + +# Tern plugin +.tern-project + +# TeXlipse plugin +.texlipse + +# STS (Spring Tool Suite) +.springBeans + +# Code Recommenders +.recommenders/ + +# Annotation Processing +.apt_generated/ +.apt_generated_test/ + +# Scala IDE specific (Scala & Java development for Eclipse) +.cache-main +.scala_dependencies +.worksheet + +# Uncomment this line if you wish to ignore the project description file. +# Typically, this file would be tracked if it contains build/dependency configurations: +#.project + +### Eclipse Patch ### +# Spring Boot Tooling +.sts4-cache/ + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar + +# Eclipse m2e generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +# JDT-specific (Eclipse Java Development Tools) + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/intellij+all,gradle,java,maven,linux,windows,macos,vim,eclipse \ No newline at end of file diff --git a/README.md b/README.md index b0eb52bb..90986d77 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@
### 자바 토이프로젝트

-> 제출자 - 최은빈 +> 제출자 - 신용호 > 출시일 - 23.04.27. > 제출일 - 23.05.10. diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..d266a6fe --- /dev/null +++ b/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group 'me.smartstore' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation(platform('org.junit:junit-bom:5.9.3')) + testImplementation('org.junit.jupiter:junit-jupiter') +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/doc/About.md b/doc/About.md new file mode 100644 index 00000000..e69de29b diff --git a/doc/SmartStore.drawio.svg b/doc/SmartStore.drawio.svg new file mode 100644 index 00000000..fe635528 --- /dev/null +++ b/doc/SmartStore.drawio.svg @@ -0,0 +1,4 @@ + + + +
===========================================
Title : SmartStore Customer Segmentation
Release Date : 23.04.24
Copyright 2023 YongHo All rights reserved.
===========================================
===========================================...
1
1
 ==============================
1. Parameter
2. Customer Data
3. Classification Summary
4. Quit
==============================
==============================...
1
1
==============================
1. Set Parameter
2. View Parameter
3. Update Parameter
4. Back
==============================
==============================...
==============================
1. Add Customer Data
2. View Customer Data
3. Update Customer Data
4. Delete Customer Data
5. Back
==============================
==============================...
1
1
==============================
1. Summary
2. Summary (Sorted By Name)
3. Summary (Sorted By Spent Time)
4. Summary (Sorted By Total Payment)
5. Back
==============================
==============================...
2
2
Which customerGroup (GENERAL (G), VIP(V), VVIP(VV)) ?
** Press 'end'. if you want to exit! **
Which customerGroup (GENERAL (G), VIP(V), VVIP(VV)) ?...
==============================
1. Minimum Spent Time
2. Minimum Total Pay
3. Back
==============================
==============================...
3
3
G
G
Input Minimum Spent Time:
** Press 'end'. if you want to exit! **
Input Minimum Spent Time:...
Input Minimum Total Pay:
** Press 'end'. if you want to exit! **
Input Minimum Total Pay:...
1
1
How many customers to input?
** Press 'end'. if you want to exit! **
How many customers to input?...
==============================
====== Customer 1 Info. ======
==============================
1. Customer Name
2. Customer ID
3. Customer Spent Time
4. Customer Total Pay
5. Back
==============================
==============================...
Input Customer's Name:
** Press 'end'. if you want to exit! **
Input Customer's Name:...
==============================
Group : NONE ( Time : null, Pay : null )
==============================
Null.

==============================
Group : GENERAL ( Time : null, Pay : null )
==============================
Null.

==============================
Group : VIP ( Time : null, Pay : null )
==============================
Null.

==============================
Group : VVIP ( Time : null, Pay : null )
==============================
Null.
==============================...
==============================
Group : GENERAL ( Time : 10, Pay : 1000000 )
==============================
No. 1 => Customer{userId='TEST1', name='TEST', spentTime=11, totalPay=10000000, customerGroup=GroupType: GENERAL
Parameter: Parameter{minimumSpentTime=10, minimumTotalPay=1000000}}
==============================...
Text is not SVG - cannot display
\ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 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 00000000..ae04661e --- /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.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..a69d9cb6 --- /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 00000000..f127cfd4 --- /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 00000000..f7628a7c --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name='KDTBE5_Java_ToyProject' \ No newline at end of file diff --git a/src/main/java/me/smartstore/AppStarter.java b/src/main/java/me/smartstore/AppStarter.java new file mode 100644 index 00000000..8332fa77 --- /dev/null +++ b/src/main/java/me/smartstore/AppStarter.java @@ -0,0 +1,45 @@ +package me.smartstore; + +import me.smartstore.core.view.MainMenu; + +/** + * 스마트스토어 메인 시작점 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class AppStarter { + private AppStarter() {} + + private static AppStarter appStarter = new AppStarter(); + + public static AppStarter getInstance() { + if (appStarter == null) { + appStarter = new AppStarter(); + } + + return appStarter; + } + + public void run() { + title(); + MainMenu.getInstance().launch(); + finish(); + } + + private void title() { + System.out.print( + """ + =========================================== + Title : SmartStore Customer Segmentation + Release Date : 23.04.24 + Copyright 2023 YongHo All rights reserved. + =========================================== + """); + } + + private void finish() { + System.out.println("Program Finished."); + } +} diff --git a/src/main/java/me/smartstore/SmartStoreApplication.java b/src/main/java/me/smartstore/SmartStoreApplication.java new file mode 100644 index 00000000..f03fb502 --- /dev/null +++ b/src/main/java/me/smartstore/SmartStoreApplication.java @@ -0,0 +1,14 @@ +package me.smartstore; + +/** + * 스마트스토어 애플리케이션 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class SmartStoreApplication { + public static void main(String[] args) { + AppStarter.getInstance().run(); + } +} diff --git a/src/main/java/me/smartstore/core/domain/Customer.java b/src/main/java/me/smartstore/core/domain/Customer.java new file mode 100644 index 00000000..93bccb31 --- /dev/null +++ b/src/main/java/me/smartstore/core/domain/Customer.java @@ -0,0 +1,110 @@ +package me.smartstore.core.domain; + +import me.smartstore.enums.CustomerType; + +/** + * 고객 정보 저장을 위한 엔티티 클래스 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class Customer { + /** 관리 번호 부여용 */ + private static Long seqNo = 0L; + + private final Long id; // 고객 관리 번호 + private String name; + private String userId; + private Integer spentTime; + private Integer payAmount; + private CustomerType customerType; + + public Customer(String name, String userId, Integer spentTime, Integer payAmount) { + synchronized (this) { + this.id = seqNo++; + } + this.name = name; + this.userId = userId; + this.spentTime = spentTime; + this.payAmount = payAmount; + this.customerType = null; + } + + public Customer(CustomerDTO dto) { + synchronized (this) { + this.id = dto.id() == null ? seqNo++ : dto.id(); + } + this.name = dto.name(); + this.userId = dto.userId(); + this.spentTime = dto.spentTime(); + this.payAmount = dto.payAmount(); + this.customerType = null; + } + + public Long getId() { + return id; + } + + public String getUserId() { + return userId; + } + + public String getName() { + return name; + } + + public Integer getSpentTime() { + return spentTime; + } + + public Integer getPayAmount() { + return payAmount; + } + + public CustomerType getCustomerType() { + return customerType; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public void setName(String name) { + this.name = name; + } + + public void setSpentTime(int spentTime) { + this.spentTime = spentTime; + } + + public void setPayAmount(int payAmount) { + this.payAmount = payAmount; + } + + public void setCustomerType(CustomerType customerType) { + this.customerType = customerType; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Customer customer = (Customer) o; + + return getId().equals(customer.getId()); + } + + @Override + public int hashCode() { + return getId().hashCode(); + } + + @Override + public String toString() { + return String.format( + "Customer{userId='%s`, name='%s', spentTime=%d, totalPayAmount=%d, group=%s}", + userId, name, spentTime, payAmount, customerType); + } +} diff --git a/src/main/java/me/smartstore/core/domain/CustomerDTO.java b/src/main/java/me/smartstore/core/domain/CustomerDTO.java new file mode 100644 index 00000000..47e621f7 --- /dev/null +++ b/src/main/java/me/smartstore/core/domain/CustomerDTO.java @@ -0,0 +1,63 @@ +package me.smartstore.core.domain; + +import me.smartstore.enums.CustomerType; + +/** + * 스마트스토어 애플리케이션 내에서 고객 정보 전달 + * + * @param id 관리 번호 + * @param name 이름 + * @param userId 사용자 ID + * @param spentTime 이용시간 + * @param payAmount 이용금액 + * @param customerType 고객 유형 + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public record CustomerDTO( + Long id, + String name, + String userId, + Integer spentTime, + Integer payAmount, + CustomerType customerType) { + + public static CustomerDTO from(Customer customer) { + return new CustomerDTO( + customer.getId(), + customer.getName(), + customer.getUserId(), + customer.getSpentTime(), + customer.getPayAmount(), + customer.getCustomerType()); + } + + public static CustomerDTO of( + String customerName, + String customerUserId, + Integer customerSpentTime, + Integer customerPayAmount) { + return new CustomerDTO( + null, customerName, customerUserId, customerSpentTime, customerPayAmount, null); + } + + @Override + public String toString() { + // Customer{userId='TEST123', name='TEST', spentTime=null, payAmount=null, group=null} + return "Customer{" + + "userId='" + + userId + + '\'' + + ", name='" + + name + + '\'' + + ", spentTime=" + + spentTime + + ", payAmount=" + + payAmount + + ", customerType=" + + customerType + + '}'; + } +} diff --git a/src/main/java/me/smartstore/core/domain/CustomerGroup.java b/src/main/java/me/smartstore/core/domain/CustomerGroup.java new file mode 100644 index 00000000..3762b106 --- /dev/null +++ b/src/main/java/me/smartstore/core/domain/CustomerGroup.java @@ -0,0 +1,43 @@ +package me.smartstore.core.domain; + +import me.smartstore.enums.CustomerType; + +/** + * 고객 유형별 세부 기준 관리를 위한 고객그룹 엔티티 클래스 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + * @see CustomerType + * @see Parameter + */ +public class CustomerGroup { + private final CustomerType customerType; + private Parameter parameter; + + public CustomerGroup(CustomerType customerType, Parameter parameter) { + this.customerType = customerType; + this.parameter = parameter; + } + + public CustomerType getCustomerType() { + return customerType; + } + + public Parameter getParameter() { + return parameter; + } + + public void setParameter(Parameter parameter) { + if (this.parameter == null) { + this.parameter = parameter; + } else { + if (parameter.getMinSpentTime() != null) { + this.parameter.setMinSpentTime(parameter.getMinSpentTime()); + } + if (parameter.getMinPayAmount() != null) { + this.parameter.setMinPayAmount(parameter.getMinPayAmount()); + } + } + } +} diff --git a/src/main/java/me/smartstore/core/domain/CustomerGroupDTO.java b/src/main/java/me/smartstore/core/domain/CustomerGroupDTO.java new file mode 100644 index 00000000..83fe0aa1 --- /dev/null +++ b/src/main/java/me/smartstore/core/domain/CustomerGroupDTO.java @@ -0,0 +1,47 @@ +package me.smartstore.core.domain; + +import me.smartstore.enums.CustomerType; + +/** + * 스마트스토어 애플리케이션 내에서 그룹 정보 전달 + * + * @param customerType 그룹별 고객 유형 + * @param parameter 그룹별 분류 기준 + */ +public record CustomerGroupDTO(CustomerType customerType, Parameter parameter) { + public static CustomerGroupDTO fromEntity(CustomerGroup customerGroup) { + return new CustomerGroupDTO(customerGroup.getCustomerType(), customerGroup.getParameter()); + } + + public static CustomerGroup toEntity(CustomerGroupDTO customerGroupDTO) { + return new CustomerGroup(customerGroupDTO.customerType(), customerGroupDTO.parameter()); + } + + public static CustomerGroupDTO of(CustomerType customerType, Parameter parameter) { + return new CustomerGroupDTO(customerType, parameter); + } + + public String groupTitle() { + StringBuilder sb = new StringBuilder(); + sb.append("==============================\n"); + sb.append("Group: ").append(customerType); + if (parameter == null) { + sb.append(" ( Time : null, Pay Amount : null )\n"); + } else { + sb.append(" ( Time :") + .append(parameter.getMinSpentTime()) + .append(", Pay Amount :") + .append(parameter.getMinPayAmount()) + .append(" )\n"); + } + sb.append("=============================="); + + return sb.toString(); + } + + @Override + public String toString() { + String parameterStr = parameter == null ? "null" : parameter.toString(); + return "CustomerType: " + customerType + "\nParameter: " + parameterStr; + } +} diff --git a/src/main/java/me/smartstore/core/domain/Parameter.java b/src/main/java/me/smartstore/core/domain/Parameter.java new file mode 100644 index 00000000..83e48d18 --- /dev/null +++ b/src/main/java/me/smartstore/core/domain/Parameter.java @@ -0,0 +1,44 @@ +package me.smartstore.core.domain; + +/** + * 고객 유형별 세부 기준 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class Parameter { + private Integer minSpentTime; + private Integer minPayAmount; + + public Parameter(Integer minSpentTime, Integer minPayAmount) { + this.minSpentTime = minSpentTime; + this.minPayAmount = minPayAmount; + } + + public Integer getMinSpentTime() { + return minSpentTime; + } + + public void setMinSpentTime(Integer minSpentTime) { + this.minSpentTime = minSpentTime; + } + + public Integer getMinPayAmount() { + return minPayAmount; + } + + public void setMinPayAmount(Integer minPayAmount) { + this.minPayAmount = minPayAmount; + } + + @Override + public String toString() { + return "Parameter{" + + "minimumSpentTime=" + + minSpentTime + + ", minimumTotalPayment=" + + minPayAmount + + '}'; + } +} diff --git a/src/main/java/me/smartstore/core/manager/CustomerGroupManager.java b/src/main/java/me/smartstore/core/manager/CustomerGroupManager.java new file mode 100644 index 00000000..35ed5fad --- /dev/null +++ b/src/main/java/me/smartstore/core/manager/CustomerGroupManager.java @@ -0,0 +1,62 @@ +package me.smartstore.core.manager; + +import java.util.Arrays; +import me.smartstore.core.domain.CustomerGroup; +import me.smartstore.enums.CustomerType; + +/** + * 스마트스토어의 모든 고객 그룹, 세분화 기준 저장 (Database 대체용) + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class CustomerGroupManager { + private static CustomerGroupManager customerGroupManager = new CustomerGroupManager(); + private final CustomerGroup[] customerGroups; + + private CustomerGroupManager() { + customerGroups = + Arrays.stream(CustomerType.values()) + .map(customerType -> new CustomerGroup(customerType, null)) + .toArray(CustomerGroup[]::new); + } + + public static CustomerGroupManager getInstance() { + if (customerGroupManager == null) { + customerGroupManager = new CustomerGroupManager(); + } + return customerGroupManager; + } + + /** + * 고객 그룹 저장 + * + * @param customerGroup 고객 그룹 + */ + public void save(CustomerGroup customerGroup) { + for (int idx = 0; idx < customerGroups.length; idx++) { + if (customerGroup.getCustomerType() == customerGroups[idx].getCustomerType()) { + customerGroups[idx] = customerGroup; + } + } + } + + /** + * @param customerType 고객 유형 + * @return 해당 고객 그룹 + */ + public CustomerGroup selectCustomerGroupByCustomerType(CustomerType customerType) { + return Arrays.stream(customerGroups) + .filter(customerGroup -> customerGroup.getCustomerType() == customerType) + .findFirst() + .orElse(null); + } + + /** + * @return 모든 고객 그룹 + */ + public CustomerGroup[] selectAllCustomerGroup() { + return Arrays.stream(customerGroups).toArray(CustomerGroup[]::new); + } +} diff --git a/src/main/java/me/smartstore/core/manager/CustomerManager.java b/src/main/java/me/smartstore/core/manager/CustomerManager.java new file mode 100644 index 00000000..a7fa0852 --- /dev/null +++ b/src/main/java/me/smartstore/core/manager/CustomerManager.java @@ -0,0 +1,222 @@ +package me.smartstore.core.manager; + +import static me.smartstore.enums.SortBy.*; +import static me.smartstore.exceptions.StoreErrorCode.*; + +import java.util.Arrays; +import java.util.Objects; +import me.smartstore.core.domain.Customer; +import me.smartstore.enums.CustomerType; +import me.smartstore.exceptions.StoreException; + +/** + * 스마트스토어 이용 고객 정보 저장 (Database 대체용) + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class CustomerManager { + private static CustomerManager customerManager = new CustomerManager(); + private static final int DEFAULT_SIZE = 20; + private static int size = 0; + private static Customer[] customers = new Customer[DEFAULT_SIZE]; + + private CustomerManager() {} + + public static CustomerManager getInstance() { + if (customerManager == null) { + customerManager = new CustomerManager(); + } + return customerManager; + } + + public int size() { + return size; + } + + public Boolean isEmpty() { + return size == 0; + } + + public Boolean isFull() { + return size == customers.length; + } + + /** + * 기존에 저장되어 있는 고객인 경우 고객 정보를 새롭게 업데이트. 그렇지 않은 경우 고객 정보를 새로 저장. + * + * @param customer 고객 정보 + * @throws StoreException 기타 데이터베이스 오류 + */ + public void save(Customer customer) throws StoreException { + for (int idx = 0; idx < size; idx++) { + if (customer.getId().equals(customers[idx].getId())) { + customers[idx] = customer; + return; + } + } + + if (isFull()) customers = Arrays.copyOf(customers, size * 2); + + customers[size++] = customer; + } + + /** + * @param id 고객정보 관리번호 + * @return 해당 관리번호의 고객정보 + * @throws StoreException 일치하는 고객정보가 없는 경우n + */ + public Customer findById(Long id) throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> id.equals(customer.getId())) + .findFirst() + .orElseThrow( + () -> { + throw new StoreException(NO_CUSTOMER); + }); + } + + /** + * @return 저장되어 있는 모든 고객정보 + * @throws StoreException 등록된 고객 정보가 없는 경우 + */ + public Customer[] selectAll() throws StoreException { + return Arrays.stream(customers).filter(Objects::nonNull).toArray(Customer[]::new); + } + + /** + * @param customerType 고객 유형 + * @return 유형이 일치하는 모든 고객정보 + * @throws StoreException 데이터베이스 내부 오류 + */ + public Customer[] selectByCustomerType(CustomerType customerType) throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> customer.getCustomerType() == customerType) + .toArray(Customer[]::new); + } + + /** + * @param customerType 고객 유형 + * @return 유형이 일치하는 모든 고객정보를 이름에 따라 오름차순으로 정렬한 결과 + * @throws StoreException 데이터베이스 내부 오류 + */ + public Customer[] selectByCustomerTypeOrderByNameAsc(CustomerType customerType) + throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> customer.getCustomerType() == customerType) + .sorted(NAME.getCustomerComparator()) + .toArray(Customer[]::new); + } + + /** + * @param customerType 고객 유형 + * @return 유형이 일치하는 모든 고객정보를 이름에 따라 내림차순으로 정렬한 결과 + * @throws StoreException 데이터베이스 내부 오류 + */ + public Customer[] selectByCustomerTypeOrderByNameDesc(CustomerType customerType) + throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> customer.getCustomerType() == customerType) + .sorted(NAME.getCustomerComparator().reversed()) + .toArray(Customer[]::new); + } + + /** + * @param customerType 고객 유형 + * @return 유형이 일치하는 모든 고객정보를 이용시간에 따라 오름차순으로 정렬한 결과 + * @throws StoreException 데이터베이스 내부 오류 + */ + public Customer[] selectByCustomerTypeOrderBySpentTimeAsc(CustomerType customerType) + throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> customer.getCustomerType() == customerType) + .sorted(SPENT_TIME.getCustomerComparator()) + .toArray(Customer[]::new); + } + + /** + * @param customerType 고객 유형 + * @return 유형이 일치하는 모든 고객정보를 이용시간에 따라 내림차순으로 정렬한 결과 + * @throws StoreException 데이터베이스 내부 오류 + */ + public Customer[] selectByCustomerTypeOrderBySpentTimeDesc(CustomerType customerType) + throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> customer.getCustomerType() == customerType) + .sorted(SPENT_TIME.getCustomerComparator().reversed()) + .toArray(Customer[]::new); + } + + /** + * @param customerType 고객 유형 + * @return 유형이 일치하는 모든 고객정보를 결제금액에 따라 오름차순으로 정렬한 결과 + * @throws StoreException 데이터베이스 내부 오류 + */ + public Customer[] selectByCustomerTypeOrderByPayAmountAsc(CustomerType customerType) + throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> customer.getCustomerType() == customerType) + .sorted(PAY_AMOUNT.getCustomerComparator()) + .toArray(Customer[]::new); + } + + /** + * @param customerType 고객 유형 + * @return 유형이 일치하는 모든 고객정보를 결제금액에 따라 내림차순으로 정렬한 결과 + * @throws StoreException 데이터베이스 내부 오류 + */ + public Customer[] selectByCustomerTypeOrderByPayAmountDesc(CustomerType customerType) + throws StoreException { + return Arrays.stream(customers) + .filter(Objects::nonNull) + .filter(customer -> customer.getCustomerType() == customerType) + .sorted(PAY_AMOUNT.getCustomerComparator().reversed()) + .toArray(Customer[]::new); + } + + /** + * @param id 삭제 대상의 관리 번호 + * @throws StoreException 존재하지 않는 관리 번호 + */ + public void deleteById(Long id) throws StoreException { + int idx = -1; + + for (int i = 0; i < size; i++) { + if (id.equals(customers[i].getId())) { + idx = i; + } + } + + if (idx == -1) throw new StoreException(NO_MATCHING_ID); + + System.arraycopy(customers, idx + 1, customers, idx, --size - idx); + customers[size] = null; + } + + /** + * @param customer 삭제할 고객정보 + * @throws StoreException 데이터베이스에 해당 고객정보가 없는 경우 + */ + public void delete(Customer customer) throws StoreException { + int idx = -1; + + for (int i = 0; i < size; i++) { + if (customer.getId().equals(customers[i].getId())) { + idx = i; + } + } + + if (idx == -1) throw new StoreException(NOT_EXIST_CUSTOMER); + + System.arraycopy(customers, idx + 1, customers, idx, --size - idx); + customers[size] = null; + } +} diff --git a/src/main/java/me/smartstore/core/service/CustomerGroupService.java b/src/main/java/me/smartstore/core/service/CustomerGroupService.java new file mode 100644 index 00000000..0d9dab25 --- /dev/null +++ b/src/main/java/me/smartstore/core/service/CustomerGroupService.java @@ -0,0 +1,84 @@ +package me.smartstore.core.service; + +import static me.smartstore.exceptions.StoreErrorCode.NO_MATCHING_GROUP; + +import java.util.Arrays; +import me.smartstore.core.domain.CustomerGroup; +import me.smartstore.core.domain.CustomerGroupDTO; +import me.smartstore.core.domain.Parameter; +import me.smartstore.core.manager.CustomerGroupManager; +import me.smartstore.enums.CustomerType; +import me.smartstore.exceptions.StoreException; + +/** + * 고객 유형 관리 서비스 제공 클래스 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class CustomerGroupService { + private static CustomerGroupService customerGroupService = new CustomerGroupService(); + private final CustomerGroupManager customerGroupManager = CustomerGroupManager.getInstance(); + private final CustomerService customerService = CustomerService.getInstance(); + + public static CustomerGroupService getInstance() { + if (customerGroupService == null) { + customerGroupService = new CustomerGroupService(); + } + return customerGroupService; + } + + /** + * 그룹 파라미터 설정 후 저장 + * + * @param customerGroupDTO 고객 그룹 DTO + * @param parameter 분류 기준 + * @return 설정이 완료된 고객 그룹 + */ + public CustomerGroupDTO setGroupParameter( + CustomerGroupDTO customerGroupDTO, Parameter parameter) { + Parameter updatedParameter = customerGroupDTO.parameter(); + + if (customerGroupDTO.parameter() != null) { + if (parameter.getMinSpentTime() != null) + updatedParameter.setMinSpentTime(parameter.getMinSpentTime()); + if (parameter.getMinPayAmount() != null) + updatedParameter.setMinPayAmount(parameter.getMinPayAmount()); + } else { + updatedParameter = parameter; + } + + CustomerGroupDTO updatedDTO = + CustomerGroupDTO.of(customerGroupDTO.customerType(), updatedParameter); + + customerGroupManager.save(CustomerGroupDTO.toEntity(updatedDTO)); + customerService.classifyAllCustomers(); + + return updatedDTO; + } + + /** + * @param customerType 고객 유형 + * @return 고객 유형과 일치하는 그룹 + * @throws StoreException 데이터베이스에 일치하는 그룹이 없을 경우 + */ + public CustomerGroupDTO find(CustomerType customerType) throws StoreException { + CustomerGroup customerGroup = + customerGroupManager.selectCustomerGroupByCustomerType(customerType); + + if (customerGroup == null) throw new StoreException(NO_MATCHING_GROUP); + + return CustomerGroupDTO.fromEntity(customerGroup); + } + + /** + * @return 데이터베이스에 저장된 모든 고객 그룹 + * @throws StoreException 데이터베이스 오류 + */ + public CustomerGroupDTO[] findAll() throws StoreException { + return Arrays.stream(customerGroupManager.selectAllCustomerGroup()) + .map(CustomerGroupDTO::fromEntity) + .toArray(CustomerGroupDTO[]::new); + } +} diff --git a/src/main/java/me/smartstore/core/service/CustomerService.java b/src/main/java/me/smartstore/core/service/CustomerService.java new file mode 100644 index 00000000..1da03c58 --- /dev/null +++ b/src/main/java/me/smartstore/core/service/CustomerService.java @@ -0,0 +1,233 @@ +package me.smartstore.core.service; + +import java.util.Arrays; +import me.smartstore.core.domain.Customer; +import me.smartstore.core.domain.CustomerDTO; +import me.smartstore.core.domain.CustomerGroupDTO; +import me.smartstore.core.manager.CustomerManager; +import me.smartstore.enums.CustomerType; +import me.smartstore.enums.SortBy; +import me.smartstore.enums.SortOrder; +import me.smartstore.exceptions.StoreException; + +/** + * 고객 정보 관리 서비스 제공 클래스 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class CustomerService { + private static CustomerService customerService = new CustomerService(); + private static final CustomerManager customerManager = CustomerManager.getInstance(); + private static final CustomerGroupService customerGroupService = + CustomerGroupService.getInstance(); + + ///////////////////////////////////////////////////////// + // 요청 사항 처리를 위한 캐싱 역할 변수들 + private static SortBy lastRequestedSortBy = SortBy.NAME; + private static SortOrder lastRequestedSortOrder = SortOrder.ASCENDING; + private static CustomerGroupDTO[] customerGroupDTOs = customerGroupService.findAll(); + private static final CustomerDTO[][] classifiedCustomerDTOs = + new CustomerDTO[customerGroupDTOs.length][]; + + public static CustomerService getInstance() { + if (customerService == null) { + customerService = new CustomerService(); + } + return customerService; + } + + /** + * @param customerDTO 고객 정보 + * @throws StoreException 데이터베이스 오류 + */ + public void save(CustomerDTO customerDTO) throws StoreException { + Customer customer = new Customer(customerDTO); + classifyCustomer(customer); + customerManager.save(customer); + } + + /** + * @return 모든 고객 정보 + * @throws StoreException 데이터베이스 오류 + */ + public CustomerDTO[] findAll() throws StoreException { + return Arrays.stream(customerManager.selectAll()) + .map(CustomerDTO::from) + .toArray(CustomerDTO[]::new); + } + + public int getNumberOfCustomers() { + return customerManager.size(); + } + + /** + * @param id 업데이트 할 고객정보 관리번호 + * @param customerDTO 업데이트할 고객정보 + * @throws StoreException 데이터베이스 오류 + */ + public void updateCustomerById(Long id, CustomerDTO customerDTO) throws StoreException { + Customer customer = customerManager.findById(id); + + if (customerDTO.name() != null) { + customer.setName(customerDTO.name()); + } + if (customerDTO.userId() != null) { + customer.setUserId(customerDTO.userId()); + } + if (customerDTO.spentTime() != null) { + customer.setSpentTime(customerDTO.spentTime()); + } + if (customerDTO.payAmount() != null) { + customer.setPayAmount(customerDTO.payAmount()); + } + + classifyCustomer(customer); + + customerManager.save(customer); + } + + /** + * 고객 관리 번호를 통한 조회 및 삭제 + * + * @param id 고객 관리 번호 + */ + public void deleteCustomerById(Long id) { + customerManager.deleteById(id); + } + + /** + * 고객정보를 바탕으로 고객 분류 + * + * @param customer 고객정보 + */ + public void classifyCustomer(Customer customer) { + for (CustomerGroupDTO customerGroupDTO : customerGroupDTOs) { + if (customerGroupDTO.parameter() == null) { + continue; + } + if (customer.getSpentTime() == null || customer.getPayAmount() == null) { + customer.setCustomerType(CustomerType.NONE); + } else { + if (customerGroupDTO.parameter().getMinSpentTime() <= customer.getSpentTime() + && customerGroupDTO.parameter().getMinPayAmount() <= customer.getPayAmount()) { + customer.setCustomerType(customerGroupDTO.customerType()); + } + } + } + if (customer.getCustomerType() == null) { + customer.setCustomerType(CustomerType.NONE); + } + } + + /** 모든 고객 분류 */ + public void classifyAllCustomers() { + customerGroupDTOs = customerGroupService.findAll(); + Customer[] customers = customerManager.selectAll(); + + for (Customer customer : customers) { + classifyCustomer(customer); + customerManager.save(customer); + } + } + + /** 고객 분류 및 요약 정보 출력. 가장 최근에 조회한 기준에 따라 자동으로 정렬. */ + public CustomerDTO[][] getClassifiedCustomerData() { + return getClassifiedCustomerData(lastRequestedSortBy, lastRequestedSortOrder); + } + + /** + * 고객 분류 결과를 기준에 따라 정렬한 결과를 뷰로 전달 + * + * @param sortBy 정렬기준 + * @param sortOrder 정렬순서 (오름차순, 내림차순) + */ + public CustomerDTO[][] getClassifiedCustomerData(SortBy sortBy, SortOrder sortOrder) { + classifyAllCustomers(); + lastRequestedSortBy = sortBy; + lastRequestedSortOrder = sortOrder; + switch (sortBy) { + case NAME -> groupingCustomersByCustomerTypeSortByName(sortOrder); + case SPENT_TIME -> groupingCustomersByCustomerTypeSortBySpentTime(sortOrder); + case PAY_AMOUNT -> groupingCustomersByCustomerTypeSortByPayAmount(sortOrder); + } + + return classifiedCustomerDTOs; + } + + /** + * 고객 분류 결과를 이름순으로 정렬. + * + * @param sortOrder 정렬순서 (오름차순, 내림차순) + */ + private void groupingCustomersByCustomerTypeSortByName(SortOrder sortOrder) { + for (int gIdx = 0; gIdx < customerGroupDTOs.length; gIdx++) { + if (sortOrder == SortOrder.ASCENDING) { + classifiedCustomerDTOs[gIdx] = + Arrays.stream( + customerManager.selectByCustomerTypeOrderByNameAsc( + customerGroupDTOs[gIdx].customerType())) + .map(CustomerDTO::from) + .toArray(CustomerDTO[]::new); + } else { + classifiedCustomerDTOs[gIdx] = + Arrays.stream( + customerManager.selectByCustomerTypeOrderByNameDesc( + customerGroupDTOs[gIdx].customerType())) + .map(CustomerDTO::from) + .toArray(CustomerDTO[]::new); + } + } + } + + /** + * 고객 분류 결과를 이용시간순으로 정렬. + * + * @param sortOrder 정렬순서 (오름차순, 내림차순) + */ + private void groupingCustomersByCustomerTypeSortBySpentTime(SortOrder sortOrder) { + for (int gIdx = 0; gIdx < customerGroupDTOs.length; gIdx++) { + if (sortOrder == SortOrder.ASCENDING) { + classifiedCustomerDTOs[gIdx] = + Arrays.stream( + customerManager.selectByCustomerTypeOrderBySpentTimeAsc( + customerGroupDTOs[gIdx].customerType())) + .map(CustomerDTO::from) + .toArray(CustomerDTO[]::new); + } else { + classifiedCustomerDTOs[gIdx] = + Arrays.stream( + customerManager.selectByCustomerTypeOrderBySpentTimeDesc( + customerGroupDTOs[gIdx].customerType())) + .map(CustomerDTO::from) + .toArray(CustomerDTO[]::new); + } + } + } + + /** + * 고객 분류 결과를 사용금액순으로 정렬. + * + * @param sortOrder 정렬순서 (오름차순, 내림차순) + */ + private void groupingCustomersByCustomerTypeSortByPayAmount(SortOrder sortOrder) { + for (int gIdx = 0; gIdx < customerGroupDTOs.length; gIdx++) { + if (sortOrder == SortOrder.ASCENDING) { + classifiedCustomerDTOs[gIdx] = + Arrays.stream( + customerManager.selectByCustomerTypeOrderByPayAmountAsc( + customerGroupDTOs[gIdx].customerType())) + .map(CustomerDTO::from) + .toArray(CustomerDTO[]::new); + } else { + classifiedCustomerDTOs[gIdx] = + Arrays.stream( + customerManager.selectByCustomerTypeOrderByPayAmountDesc( + customerGroupDTOs[gIdx].customerType())) + .map(CustomerDTO::from) + .toArray(CustomerDTO[]::new); + } + } + } +} diff --git a/src/main/java/me/smartstore/core/view/AbstractMenu.java b/src/main/java/me/smartstore/core/view/AbstractMenu.java new file mode 100644 index 00000000..4914cc31 --- /dev/null +++ b/src/main/java/me/smartstore/core/view/AbstractMenu.java @@ -0,0 +1,54 @@ +package me.smartstore.core.view; + +import static me.smartstore.exceptions.StoreErrorCode.INVALID_FORMAT; +import static me.smartstore.exceptions.StoreErrorCode.INVALID_INPUT; + +import me.smartstore.exceptions.StoreException; +import me.smartstore.utils.ScannerUtility; + +/** + * 메뉴 출력 및 선택 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public abstract class AbstractMenu { + /** 선택 가능 메뉴 항목 */ + private final String[] items; + + public AbstractMenu(String[] items) { + this.items = items; + } + + /** 메뉴 출력 */ + void show() { + StringBuilder menuBuilder = new StringBuilder().append("\n==============================\n"); + for (int i = 0; i < items.length; i++) { + menuBuilder.append(i + 1).append(". ").append(items[i]).append("\n"); + } + menuBuilder.append("=============================="); + System.out.println(menuBuilder); + } + + /** + * 메뉴 입력 + * + * @return 입력된 메뉴 번호 + */ + int selectMenuNumber() throws StoreException { + System.out.print("Choose One: "); + + int selection = ScannerUtility.getIntegerInputSafely(); + + if (selection == -1) { + throw new StoreException(INVALID_FORMAT); + } + + if (selection < 1 || selection > items.length) { + throw new StoreException(INVALID_INPUT); + } + + return selection; + } +} diff --git a/src/main/java/me/smartstore/core/view/ClassificationSummaryMenu.java b/src/main/java/me/smartstore/core/view/ClassificationSummaryMenu.java new file mode 100644 index 00000000..ded6e47f --- /dev/null +++ b/src/main/java/me/smartstore/core/view/ClassificationSummaryMenu.java @@ -0,0 +1,153 @@ +package me.smartstore.core.view; + +import static me.smartstore.enums.SmartStoreMessage.INPUT_SORT_ORDER; +import static me.smartstore.enums.SmartStoreMessage.PRESS_END_MSG; +import static me.smartstore.enums.SortBy.*; +import static me.smartstore.exceptions.StoreErrorCode.INPUT_END; +import static me.smartstore.utils.StoreUtility.convertInputStrToSortOrder; + +import me.smartstore.core.domain.CustomerDTO; +import me.smartstore.core.domain.CustomerGroupDTO; +import me.smartstore.core.service.CustomerGroupService; +import me.smartstore.core.service.CustomerService; +import me.smartstore.enums.SortBy; +import me.smartstore.enums.SortOrder; +import me.smartstore.exceptions.StoreException; +import me.smartstore.utils.ScannerUtility; + +/** + * 고객 분류 정보 출력 메뉴 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class ClassificationSummaryMenu extends AbstractMenu { + private static ClassificationSummaryMenu classificationSummaryMenu = + new ClassificationSummaryMenu(); + + private static final CustomerGroupService customerGroupService = + CustomerGroupService.getInstance(); + private static final CustomerService customerService = CustomerService.getInstance(); + + private ClassificationSummaryMenu() { + super( + new String[] { + "Summary", + "Summary (Sorted By Name)", + "Summary (Sorted By Spent Time)", + "Summary (Sorted By Total Pay Amount)", + "Back" + }); + } + + public static ClassificationSummaryMenu getInstance() { + if (classificationSummaryMenu == null) { + classificationSummaryMenu = new ClassificationSummaryMenu(); + } + return classificationSummaryMenu; + } + + public void launch() { + loop: + while (true) { + classificationSummaryMenu.show(); + try { + switch (classificationSummaryMenu.selectMenuNumber()) { + // 일반 요약 정보 출력 - 가장 최근에 조회한 정렬 기준에 따라 자동으로 변환 + case 1 -> displayClassifiedCustomerData(); + + // 고객 그룹별 이름순 정렬 + case 2 -> { + while (true) { + try { + displayClassifiedCustomerDataSortBy(NAME, inputSortOrder()); + } catch (StoreException e) { + if (e.getErrorCode() == INPUT_END) break; + System.out.println(e.getMessage()); + } + } + } + + // 고객 그룹별 이용시간순 정렬 + case 3 -> { + while (true) { + try { + displayClassifiedCustomerDataSortBy(SPENT_TIME, inputSortOrder()); + } catch (StoreException e) { + if (e.getErrorCode() == INPUT_END) break; + System.out.println(e.getMessage()); + } + } + } + + // 고객 그룹별 사용금액순 정렬 + case 4 -> { + while (true) { + try { + displayClassifiedCustomerDataSortBy(PAY_AMOUNT, inputSortOrder()); + } catch (StoreException e) { + if (e.getErrorCode() == INPUT_END) break; + System.out.println(e.getMessage()); + } + } + } + + // 이전 메뉴 + case 5 -> { + break loop; + } + } + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } + + /** + * @return 정렬 방향 (오름차순, 내림차순) + * @throws StoreException 종료 선택시 + */ + private SortOrder inputSortOrder() throws StoreException { + while (true) { + System.out.println(INPUT_SORT_ORDER + "\n" + PRESS_END_MSG); + try { + String input = ScannerUtility.getInput(); + if ("end".equalsIgnoreCase(input)) throw new StoreException(INPUT_END); + return convertInputStrToSortOrder(input); + } catch (StoreException e) { + System.out.println(e.getMessage()); + if (e.getErrorCode() == INPUT_END) throw new StoreException(INPUT_END); + } + } + } + + private void displayClassifiedCustomerData() { + CustomerGroupDTO[] customerGroupDTOs = customerGroupService.findAll(); + CustomerDTO[][] classifiedCustomerDTOs = customerService.getClassifiedCustomerData(); + + displayClassifiedCustomerData(customerGroupDTOs, classifiedCustomerDTOs); + } + + private void displayClassifiedCustomerDataSortBy(SortBy sortBy, SortOrder sortOrder) { + CustomerGroupDTO[] customerGroupDTOs = customerGroupService.findAll(); + CustomerDTO[][] classifiedCustomerDTOs = + customerService.getClassifiedCustomerData(sortBy, sortOrder); + + displayClassifiedCustomerData(customerGroupDTOs, classifiedCustomerDTOs); + } + + private void displayClassifiedCustomerData( + CustomerGroupDTO[] customerGroupDTOs, CustomerDTO[][] classifiedCustomerDTOs) { + for (int gIdx = 0; gIdx < customerGroupDTOs.length; gIdx++) { + System.out.println("\n" + customerGroupDTOs[gIdx].groupTitle()); + + if (classifiedCustomerDTOs[gIdx] == null || classifiedCustomerDTOs[gIdx].length == 0) + System.out.println("Null."); + + for (int cIdx = 0; cIdx < classifiedCustomerDTOs[gIdx].length; cIdx++) { + System.out.println("No. " + (cIdx + 1) + " => " + classifiedCustomerDTOs[gIdx][cIdx]); + } + } + } +} diff --git a/src/main/java/me/smartstore/core/view/CustomerMenu.java b/src/main/java/me/smartstore/core/view/CustomerMenu.java new file mode 100644 index 00000000..6a51d543 --- /dev/null +++ b/src/main/java/me/smartstore/core/view/CustomerMenu.java @@ -0,0 +1,152 @@ +package me.smartstore.core.view; + +import static me.smartstore.enums.SmartStoreMessage.INPUT_NUMBER_OF_CUSTOMERS; +import static me.smartstore.enums.SmartStoreMessage.PRESS_END_MSG; +import static me.smartstore.exceptions.StoreErrorCode.*; +import static me.smartstore.utils.ScannerUtility.getInput; +import static me.smartstore.utils.ScannerUtility.getIntegerInputSafely; + +import me.smartstore.core.domain.CustomerDTO; +import me.smartstore.core.service.CustomerService; +import me.smartstore.exceptions.StoreException; + +/** + * 고객 정보 관리 메뉴 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class CustomerMenu extends AbstractMenu { + private static CustomerMenu customerMenu = new CustomerMenu(); + private static final CustomerService customerService = CustomerService.getInstance(); + private static final CustomerSubMenu customerSubMenu = CustomerSubMenu.getInstance(); + + /** 고객 정보 캐싱 */ + private static CustomerDTO[] dtoCache = new CustomerDTO[] {}; + + private CustomerMenu() { + super( + new String[] { + "Add Customer Data", + "View Customer Data", + "Update Customer Data", + "Delete Customer Data", + "Back" + }); + } + + public static CustomerMenu getInstance() { + if (customerMenu == null) { + customerMenu = new CustomerMenu(); + } + return customerMenu; + } + + public void launch() { + loop: + while (true) { + customerMenu.show(); + try { + switch (customerMenu.selectMenuNumber()) { + + // 고객 등록 + case 1 -> { + int numberOfCustomers = inputNumberOfCustomers(); + for (int idx = 0; idx < numberOfCustomers; idx++) { + System.out.println("\n====== Customer " + (idx + 1) + ". Info. ======"); + CustomerDTO newCustomer = customerSubMenu.inputCustomerInfo(); + customerService.save(newCustomer); + } + } + + // 고객 명단 확인 + case 2 -> showCustomerInfo(); + + // 고객 정보 수정 + case 3 -> { + showCustomerInfo(); + int customerNumber = inputCustomerNumber(); + Long id = dtoCache[customerNumber - 1].id(); + CustomerDTO updateDTO = customerSubMenu.inputCustomerInfo(); + customerService.updateCustomerById(id, updateDTO); + } + + // 고객 정보 삭제 + case 4 -> { + showCustomerInfo(); + int customerNumber = inputCustomerNumber(); + Long id = dtoCache[customerNumber - 1].id(); + customerService.deleteCustomerById(id); + showCustomerInfo(); + } + + case 5 -> { + break loop; + } + } + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } + + /** + * 현재 등록된 고객 명단 출력 + * + * @throws StoreException 등록된 고객 정보가 없음 + */ + private void showCustomerInfo() throws StoreException { + // No. 1 => Customer{userId='TEST123', name='TEST', spentTime=null, totalPay=null, group=null} + dtoCache = customerService.findAll(); + if (dtoCache.length == 0) { + throw new StoreException(NO_CUSTOMER); + } + + System.out.println("\n======= Customer Info. ======="); + for (int idx = 0; idx < dtoCache.length; idx++) { + System.out.println("No. " + (idx + 1) + " => " + dtoCache[idx]); + } + } + + /** + * @return 새로 등록할 고객수 + * @throws StoreException 종료 선택시 + */ + private int inputNumberOfCustomers() throws StoreException { + while (true) { + System.out.println(INPUT_NUMBER_OF_CUSTOMERS + "\n" + PRESS_END_MSG); + String input = getInput(); + if ("end".equalsIgnoreCase(input)) throw new StoreException(INPUT_END); + try { + int numberOfCustomers = Integer.parseInt(input); + if (numberOfCustomers == -1) { + throw new StoreException(INVALID_FORMAT); + } + return numberOfCustomers; + } catch (NumberFormatException e) { + System.out.println(INVALID_FORMAT.getMessage()); + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } + + /** + * @return 출력된 명단 중 수정하고자 하는 고객의 번호 + */ + private int inputCustomerNumber() { + while (true) { + System.out.println("Which customer ( 1 ~ " + customerService.getNumberOfCustomers() + " )? "); + try { + int customerNumber = getIntegerInputSafely(); + if (customerNumber < 1 || customerNumber > customerService.getNumberOfCustomers()) { + throw new StoreException(INVALID_FORMAT); + } + return customerNumber; + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } +} diff --git a/src/main/java/me/smartstore/core/view/CustomerSubMenu.java b/src/main/java/me/smartstore/core/view/CustomerSubMenu.java new file mode 100644 index 00000000..967e94b5 --- /dev/null +++ b/src/main/java/me/smartstore/core/view/CustomerSubMenu.java @@ -0,0 +1,119 @@ +package me.smartstore.core.view; + +import static me.smartstore.enums.SmartStoreMessage.*; +import static me.smartstore.exceptions.StoreErrorCode.*; + +import me.smartstore.core.domain.CustomerDTO; +import me.smartstore.exceptions.StoreErrorCode; +import me.smartstore.exceptions.StoreException; +import me.smartstore.utils.ScannerUtility; + +/** + * 고객 세부 정보 관리 메뉴 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class CustomerSubMenu extends AbstractMenu { + private static final CustomerSubMenu customerSubMenu = new CustomerSubMenu(); + + private CustomerSubMenu() { + super( + new String[] { + "Customer Name", "Customer ID", "Customer Spent Time", "Customer Total Pay Amount", "Back" + }); + } + + public static CustomerSubMenu getInstance() { + return customerSubMenu; + } + + /** + * @return 입력 받은 고객 세부 정보 + */ + public CustomerDTO inputCustomerInfo() { + String customerName = null; + String customerID = null; + Integer customerSpentTime = null; + Integer customerPayAmount = null; + + loop: + while (true) { + customerSubMenu.show(); + + try { + switch (customerSubMenu.selectMenuNumber()) { + case 1 -> customerName = customerSubMenu.inputCustomerName(); + case 2 -> customerID = customerSubMenu.inputCustomerId(); + case 3 -> customerSpentTime = customerSubMenu.inputCustomerSpentTime(); + case 4 -> customerPayAmount = customerSubMenu.inputCustomerPayAmount(); + case 5 -> { + break loop; + } + } + } catch (StoreException e) { + System.out.println(e.getMessage()); + if (e.getErrorCode() == INPUT_END) break; + } + } + + return CustomerDTO.of(customerName, customerID, customerSpentTime, customerPayAmount); + } + + /** + * @return 입력 받은 고객 이름 + * @throws StoreException 종료 선택시 + */ + private String inputCustomerName() throws StoreException { + System.out.println(INPUT_CUSTOMER_NAME + "\n" + PRESS_END_MSG); + String input = ScannerUtility.getInput(); + if ("end".equalsIgnoreCase(input)) throw new StoreException(INPUT_END); + return input; + } + + /** + * @return 입력 받은 고객 ID + * @throws StoreException 종료 선택시 + */ + private String inputCustomerId() throws StoreException { + System.out.println(INPUT_CUSTOMER_ID + "\n" + PRESS_END_MSG); + String input = ScannerUtility.getInput(); + if ("end".equalsIgnoreCase(input)) throw new StoreException(INPUT_END); + return input; + } + + /** + * @return 입력 받은 고객의 이용 시간 + * @throws StoreException 종료 선택시 + */ + private int inputCustomerSpentTime() throws StoreException { + while (true) { + System.out.println(INPUT_CUSTOMER_SPENT_TIME + "\n" + PRESS_END_MSG); + String input = ScannerUtility.getInput(); + if ("end".equalsIgnoreCase(input)) throw new StoreException(INPUT_END); + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + System.out.println(StoreErrorCode.INVALID_FORMAT.getMessage()); + } + } + } + + /** + * @return 입력 받은 고객의 결제 금액 + * @throws StoreException 종료 선택시 + */ + private int inputCustomerPayAmount() throws StoreException { + while (true) { + System.out.println(INPUT_CUSTOMER_PAY_AMOUNT + "\n" + PRESS_END_MSG); + String input = ScannerUtility.getInput(); + if ("end".equalsIgnoreCase(input)) throw new StoreException(INPUT_END); + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + System.out.println(StoreErrorCode.INVALID_FORMAT.getMessage()); + } + } + } +} diff --git a/src/main/java/me/smartstore/core/view/MainMenu.java b/src/main/java/me/smartstore/core/view/MainMenu.java new file mode 100644 index 00000000..11fb7931 --- /dev/null +++ b/src/main/java/me/smartstore/core/view/MainMenu.java @@ -0,0 +1,51 @@ +package me.smartstore.core.view; + +import me.smartstore.exceptions.StoreException; + +/** + * 메인 메뉴 화면 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class MainMenu extends AbstractMenu { + private static MainMenu mainMenu = new MainMenu(); + + private MainMenu() { + super(new String[] {"Parameter", "Customer Data", "Classification Summary", "Quit"}); + } + + public static MainMenu getInstance() { + if (mainMenu == null) { + mainMenu = new MainMenu(); + } + return mainMenu; + } + + public void launch() { + loop: + while (true) { + mainMenu.show(); + try { + switch (mainMenu.selectMenuNumber()) { + // 고객 유형 세분화 기준 설정 + case 1 -> ParameterMenu.getInstance().launch(); + + // 고객 정보 관리 + case 2 -> CustomerMenu.getInstance().launch(); + + // 고객 정보 요약 + case 3 -> ClassificationSummaryMenu.getInstance().launch(); + + // 종료 + case 4 -> { + break loop; + } + } + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } +} diff --git a/src/main/java/me/smartstore/core/view/ParameterMenu.java b/src/main/java/me/smartstore/core/view/ParameterMenu.java new file mode 100644 index 00000000..0e923c6a --- /dev/null +++ b/src/main/java/me/smartstore/core/view/ParameterMenu.java @@ -0,0 +1,116 @@ +package me.smartstore.core.view; + +import static me.smartstore.enums.SmartStoreMessage.INPUT_CUSTOMER_GROUP_MSG; +import static me.smartstore.enums.SmartStoreMessage.PRESS_END_MSG; +import static me.smartstore.exceptions.StoreErrorCode.*; +import static me.smartstore.utils.StoreUtility.convertInputStrToCustomerType; + +import me.smartstore.core.domain.CustomerGroupDTO; +import me.smartstore.core.service.CustomerGroupService; +import me.smartstore.enums.CustomerType; +import me.smartstore.exceptions.StoreException; +import me.smartstore.utils.ScannerUtility; + +/** + * 고객 유형 세분화 기준 설정 메뉴 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class ParameterMenu extends AbstractMenu { + private static ParameterMenu parameterMenu = new ParameterMenu(); + private static final ParameterSubMenu parameterSubMenu = ParameterSubMenu.getInstance(); + private static final CustomerGroupService customerGroupService = + CustomerGroupService.getInstance(); + + private ParameterMenu() { + super(new String[] {"Set Parameter", "View Parameter", "Update Parameter", "Back"}); + } + + public static ParameterMenu getInstance() { + if (parameterMenu == null) { + parameterMenu = new ParameterMenu(); + } + return parameterMenu; + } + + public void launch() { + loop: + while (true) { + parameterMenu.show(); + try { + switch (parameterMenu.selectMenuNumber()) { + // 기준 초기 설정 + case 1 -> { + while (true) { + CustomerType customerType = inputCustomerType(); + CustomerGroupDTO customerGroupDTO = customerGroupService.find(customerType); + + if (customerGroupDTO.parameter() != null) { + System.out.println(GROUP_ALREADY_SET.getMessage()); + } else { + customerGroupDTO = + customerGroupService.setGroupParameter( + customerGroupDTO, parameterSubMenu.inputParameter()); + } + + System.out.println(customerGroupDTO); + } + } + + // 설정된 기준 보기 + case 2 -> { + while (true) { + CustomerType customerType = inputCustomerType(); + System.out.println(customerGroupService.find(customerType)); + } + } + + // 기준 수정 + case 3 -> { + while (true) { + CustomerType customerType = inputCustomerType(); + CustomerGroupDTO customerGroupDTO = customerGroupService.find(customerType); + + if (customerGroupDTO.parameter() == null) throw new StoreException(NO_PARAMETER); + + customerGroupDTO = + customerGroupService.setGroupParameter( + customerGroupDTO, parameterSubMenu.inputParameter()); + + System.out.println(customerGroupDTO); + } + } + + // 이전 메뉴 + case 4 -> { + break loop; + } + } + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } + + /** + * @return 입력받은 고객 유형 + * @throws StoreException 종료 선택시, 공백 입력시 발생 + */ + private CustomerType inputCustomerType() throws StoreException { + while (true) { + System.out.println(INPUT_CUSTOMER_GROUP_MSG + "\n" + PRESS_END_MSG); + String input = ScannerUtility.getInput().toUpperCase(); + + if ("end".equalsIgnoreCase(input)) throw new StoreException(INPUT_END); + + try { + if ("".equals(input)) throw new StoreException(NULL_INPUT); + return convertInputStrToCustomerType(input); + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } +} diff --git a/src/main/java/me/smartstore/core/view/ParameterSubMenu.java b/src/main/java/me/smartstore/core/view/ParameterSubMenu.java new file mode 100644 index 00000000..00072114 --- /dev/null +++ b/src/main/java/me/smartstore/core/view/ParameterSubMenu.java @@ -0,0 +1,99 @@ +package me.smartstore.core.view; + +import static me.smartstore.enums.SmartStoreMessage.*; +import static me.smartstore.enums.SmartStoreMessage.PRESS_END_MSG; +import static me.smartstore.exceptions.StoreErrorCode.*; + +import me.smartstore.core.domain.Parameter; +import me.smartstore.exceptions.StoreErrorCode; +import me.smartstore.exceptions.StoreException; +import me.smartstore.utils.ScannerUtility; + +/** + * 고객 유형별 기준 설정 메뉴 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class ParameterSubMenu extends AbstractMenu { + private static ParameterSubMenu parameterSubMenu = new ParameterSubMenu(); + + private ParameterSubMenu() { + super(new String[] {"Minimum Spent Time", "Minimum Pay Amount", "Back"}); + } + + /** + * @return Singleton 객체 반환 + */ + public static ParameterSubMenu getInstance() { + if(parameterSubMenu == null) { + parameterSubMenu = new ParameterSubMenu(); + } + return parameterSubMenu; + } + + /** + * @return 입력받은 고객 유형 분류 기준 + */ + public Parameter inputParameter() { + Integer minimumSpentTime = null; + Integer minimumPayAmount = null; + + while (true) { + parameterSubMenu.show(); + + try { + switch (parameterSubMenu.selectMenuNumber()) { + case 1 -> minimumSpentTime = inputMinimumSpentTime(); + case 2 -> minimumPayAmount = inputMinimumPayAmount(); + case 3 -> { + return new Parameter(minimumSpentTime, minimumPayAmount); + } + } + } catch (StoreException e) { + System.out.println(e.getMessage()); + } + } + } + + /** + * @return 입력받은 최소 이용시간 + * @throws StoreException 종료 선택시. + */ + private int inputMinimumSpentTime() throws StoreException { + while (true) { + System.out.println(INPUT_MINIMUM_SPENT_TIME_MSG + "\n" + PRESS_END_MSG); + + String input = ScannerUtility.getInput(); + + if ("end".equals(input)) throw new StoreException(INPUT_END); + + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + System.out.println(StoreErrorCode.INVALID_FORMAT.getMessage()); + } + } + } + + /** + * @return 입력받은 최소 결제금액 + * @throws StoreException 종료 선택시. + */ + private int inputMinimumPayAmount() throws StoreException { + while (true) { + System.out.println(INPUT_MINIMUM_PAY_AMOUNT_MSG + "\n" + PRESS_END_MSG); + + String input = ScannerUtility.getInput(); + + if ("end".equals(input)) throw new StoreException(INPUT_END); + + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + System.out.println(StoreErrorCode.INVALID_FORMAT.getMessage()); + } + } + } +} diff --git a/src/main/java/me/smartstore/enums/CustomerType.java b/src/main/java/me/smartstore/enums/CustomerType.java new file mode 100644 index 00000000..ebd872f6 --- /dev/null +++ b/src/main/java/me/smartstore/enums/CustomerType.java @@ -0,0 +1,50 @@ +package me.smartstore.enums; + +import java.util.Collections; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 고객 유형 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public enum CustomerType { + NONE("N", "해당없음"), + GENERAL("G", "일반고객"), + VIP("V", "우수고객"), + VVIP("VV", "최우수고객"); + + private static final Map ABBREVIATION_MAP; + + static { + Map map = + Stream.of(values()) + .collect(Collectors.toMap(CustomerType::getAbbreviation, CustomerType::name)); + Stream.of(values()).forEach(type -> map.put(type.name(), type.name())); + ABBREVIATION_MAP = Collections.unmodifiableMap(map); + } + + private final String abbreviation; + private final String description; + + CustomerType(String abbreviation, String description) { + this.abbreviation = abbreviation; + this.description = description; + } + + public String getAbbreviation() { + return abbreviation; + } + + public String getDescription() { + return description; + } + + public static CustomerType of(final String valueStr) { + return CustomerType.valueOf(ABBREVIATION_MAP.get(valueStr)); + } +} diff --git a/src/main/java/me/smartstore/enums/SmartStoreMessage.java b/src/main/java/me/smartstore/enums/SmartStoreMessage.java new file mode 100644 index 00000000..336295ed --- /dev/null +++ b/src/main/java/me/smartstore/enums/SmartStoreMessage.java @@ -0,0 +1,37 @@ +package me.smartstore.enums; + +/** + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public enum SmartStoreMessage { + // Customer Sub Menu + INPUT_NUMBER_OF_CUSTOMERS("How many customers to input?"), + INPUT_CUSTOMER_NAME("Input Customer's Name:"), + INPUT_CUSTOMER_ID("Input Customer's ID:"), + INPUT_CUSTOMER_SPENT_TIME("Input Customer's Spent Time:"), + INPUT_CUSTOMER_PAY_AMOUNT("Input Customer's Total Pay Amount:"), + + // Parameter Sub Menu Message + INPUT_MINIMUM_SPENT_TIME_MSG("Input Minimum Spent Time."), + INPUT_MINIMUM_PAY_AMOUNT_MSG("Input Minimum Total Pay Amount."), + + // Customer Group Menu Message + INPUT_CUSTOMER_GROUP_MSG("Which group (GENERAL (G), VIP (V), VVIP (VV))?"), + + INPUT_SORT_ORDER("Which order (ASCENDING (A), DESCENDING (D))?"), + + PRESS_END_MSG("** Press 'end', if you want to exit! **"); + + private final String detailMessage; + + SmartStoreMessage(String detailMessage) { + this.detailMessage = detailMessage; + } + + @Override + public String toString() { + return detailMessage; + } +} diff --git a/src/main/java/me/smartstore/enums/SortBy.java b/src/main/java/me/smartstore/enums/SortBy.java new file mode 100644 index 00000000..634a078b --- /dev/null +++ b/src/main/java/me/smartstore/enums/SortBy.java @@ -0,0 +1,26 @@ +package me.smartstore.enums; + +import me.smartstore.core.domain.Customer; + +import java.util.Comparator; + +/** + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public enum SortBy { + NAME(Comparator.comparing(Customer::getName)), + SPENT_TIME(Comparator.comparing(Customer::getSpentTime)), + PAY_AMOUNT(Comparator.comparing(Customer::getPayAmount)); + + private final Comparator customerComparator; + + SortBy(Comparator customerComparator) { + this.customerComparator = customerComparator; + } + + public Comparator getCustomerComparator() { + return customerComparator; + } +} diff --git a/src/main/java/me/smartstore/enums/SortOrder.java b/src/main/java/me/smartstore/enums/SortOrder.java new file mode 100644 index 00000000..3ab47712 --- /dev/null +++ b/src/main/java/me/smartstore/enums/SortOrder.java @@ -0,0 +1,25 @@ +package me.smartstore.enums; + +/** + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public enum SortOrder { + A("Ascending"), + D("Descending"), + ASCENDING("Ascending"), + DESCENDING("Descending"); + + private final String sortOrder; + + SortOrder(String sortOrder) { + this.sortOrder = sortOrder; + } + + public SortOrder replaceAbbreviation() { + if (this == A) return ASCENDING; + else if (this == D) return DESCENDING; + else return this; + } +} diff --git a/src/main/java/me/smartstore/exceptions/StoreErrorCode.java b/src/main/java/me/smartstore/exceptions/StoreErrorCode.java new file mode 100644 index 00000000..29d58f59 --- /dev/null +++ b/src/main/java/me/smartstore/exceptions/StoreErrorCode.java @@ -0,0 +1,35 @@ +package me.smartstore.exceptions; + +/** + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public enum StoreErrorCode { + UNKNOWN_TYPE("Can't identify customer type"), + NOT_EXIST_CUSTOMER("Customer doesn't exist."), + NO_MATCHING_ID("No matching id."), + NO_MATCHING_GROUP("No matching group."), + NO_CUSTOMER("No Customers. Please input one first."), + CANT_SORT("Elements in Array has null. Array can't be sorted."), + NULL_INPUT("Null Input. Please input something."), + EMPTY_INPUT("Empty Input. Please input something."), + INVALID_INPUT("Invalid Input. Please try again."), + INVALID_TYPE("Invalid Type for Input. Please try again."), + INVALID_FORMAT("Invalid Format for Input. Please try again."), + GROUP_ALREADY_SET("group already exists."), + NO_PARAMETER("No parameter. Set the parameter first"), + INTERNAL_ERROR("Internal Error."), + INPUT_END("END is pressed. Exit this menu."), + END_MSG("END"); + + private final String message; + + StoreErrorCode(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/me/smartstore/exceptions/StoreException.java b/src/main/java/me/smartstore/exceptions/StoreException.java new file mode 100644 index 00000000..84030078 --- /dev/null +++ b/src/main/java/me/smartstore/exceptions/StoreException.java @@ -0,0 +1,40 @@ +package me.smartstore.exceptions; + +/** + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class StoreException extends RuntimeException { + private final StoreErrorCode storeErrorCode; + private final String message; + + public StoreException() { + this.storeErrorCode = StoreErrorCode.INTERNAL_ERROR; + this.message = StoreErrorCode.INTERNAL_ERROR.getMessage(); + } + + public StoreException(StoreErrorCode storeErrorCode) { + this.storeErrorCode = storeErrorCode; + this.message = storeErrorCode.getMessage(); + } + + public StoreException(StoreErrorCode storeErrorCode, String message) { + this.storeErrorCode = storeErrorCode; + this.message = message; + } + + public StoreException(String message) { + this.storeErrorCode = StoreErrorCode.INTERNAL_ERROR; + this.message = message; + } + + public StoreErrorCode getErrorCode() { + return storeErrorCode; + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/src/main/java/me/smartstore/utils/ScannerUtility.java b/src/main/java/me/smartstore/utils/ScannerUtility.java new file mode 100644 index 00000000..7e8c3227 --- /dev/null +++ b/src/main/java/me/smartstore/utils/ScannerUtility.java @@ -0,0 +1,38 @@ +package me.smartstore.utils; + +import me.smartstore.exceptions.StoreException; + +import java.util.NoSuchElementException; +import java.util.Scanner; + +import static me.smartstore.exceptions.StoreErrorCode.EMPTY_INPUT; +import static me.smartstore.exceptions.StoreErrorCode.INTERNAL_ERROR; + +/** + * 사용자로부터 입력을 받기 위한 유틸리티 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class ScannerUtility { + private static final Scanner scanner = new Scanner(System.in); + + /** + * @return 정수로 변환된 결과. 공백일 경우 -1. + */ + public static int getIntegerInputSafely() { + String converted = scanner.nextLine().replaceAll("[^0-9]", ""); + return "".equals(converted) ? -1 : Integer.parseInt(converted); + } + + public static String getInput() throws StoreException { + try { + return scanner.nextLine(); + } catch (NoSuchElementException e) { + throw new StoreException(EMPTY_INPUT); + } catch (IllegalStateException e) { + throw new StoreException(INTERNAL_ERROR); + } + } +} diff --git a/src/main/java/me/smartstore/utils/StoreUtility.java b/src/main/java/me/smartstore/utils/StoreUtility.java new file mode 100644 index 00000000..1e863c89 --- /dev/null +++ b/src/main/java/me/smartstore/utils/StoreUtility.java @@ -0,0 +1,32 @@ +package me.smartstore.utils; + +import me.smartstore.enums.CustomerType; +import me.smartstore.enums.SortOrder; +import me.smartstore.exceptions.StoreException; + +import static me.smartstore.exceptions.StoreErrorCode.INVALID_FORMAT; + +/** + * 스마트스토어에 필요한 부가 기능 제공 유틸리티 + * + * @author YongHo Shin + * @version v1.0 + * @since 2023-05-10 + */ +public class StoreUtility { + public static CustomerType convertInputStrToCustomerType(String input) throws StoreException { + try { + return CustomerType.of(input); + } catch (RuntimeException e) { + throw new StoreException(INVALID_FORMAT); + } + } + + public static SortOrder convertInputStrToSortOrder(String input) throws StoreException { + try { + return SortOrder.valueOf(input.toUpperCase()).replaceAbbreviation(); + } catch (IllegalArgumentException e) { + throw new StoreException(INVALID_FORMAT); + } + } +} diff --git a/src/test/java/me/smartstore/core/manager/CustomerGroupManagerTest.java b/src/test/java/me/smartstore/core/manager/CustomerGroupManagerTest.java new file mode 100644 index 00000000..6d0d2a9a --- /dev/null +++ b/src/test/java/me/smartstore/core/manager/CustomerGroupManagerTest.java @@ -0,0 +1,98 @@ +package me.smartstore.core.manager; + +import static me.smartstore.enums.CustomerType.GENERAL; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Arrays; +import me.smartstore.core.domain.CustomerGroup; +import me.smartstore.core.domain.Parameter; +import me.smartstore.enums.CustomerType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +class CustomerGroupManagerTest { + private static final CustomerGroupManager customerGroupManager = + CustomerGroupManager.getInstance(); + + @AfterEach + void restoreCustomerGroup() { + // Instance 를 직접 사용하기 때문에 각 테스트가 끝난 이후 직접 초기화 해주어야 각각의 테스트가 의도한대로 수행됨 + // 이 과정이 없을 경우 먼저 수행된 테스트의 결과가 이후 테스트에 영향을 미침. + Arrays.stream(CustomerType.values()) + .forEach(type -> customerGroupManager.save(new CustomerGroup(type, null))); + } + + @DisplayName("[SAVE] 정상 고객 그룹 - 저장 성공") + @Test + void givenCustomerGroup_whenSaves_thenSavesCustomerGroup() { + // Given + Parameter parameter = new Parameter(123, 123456); + CustomerGroup testGroup = new CustomerGroup(GENERAL, parameter); + + // When + customerGroupManager.save(testGroup); + CustomerGroup updated = customerGroupManager.selectCustomerGroupByCustomerType(GENERAL); + + // Then + assertEquals(GENERAL, updated.getCustomerType()); + assertEquals(parameter, updated.getParameter()); + assertEquals(123, updated.getParameter().getMinSpentTime()); + assertEquals(123456, updated.getParameter().getMinPayAmount()); + } + + @DisplayName("[SAVE] 알 수 없는 고객 그룹 - 저장 실패") + @ParameterizedTest(name = "고객 유형 (CustomerType): {0}") + @EnumSource(CustomerType.class) + void givenUnknownCustomerType_whenSave_thenChangesNothing(CustomerType customerType) { + // Given + Parameter parameter = new Parameter(123, 123456); + CustomerGroup testGroup = new CustomerGroup(null, parameter); + + // When + customerGroupManager.save(testGroup); + CustomerGroup actual = customerGroupManager.selectCustomerGroupByCustomerType(customerType); + + // Then + assertNull(actual.getParameter()); + } + + @DisplayName("[SELECT] 고객 유형별 그룹 조회 - 조회 성공") + @ParameterizedTest(name = "고객 유형 (CustomerType) : {0}") + @EnumSource(CustomerType.class) + void givenCustomerType_whenSelectCustomerGroup_thenReturnsSelectedCustomerGroup( + CustomerType customerType) { + // Given + + // Given && When + CustomerGroup actual = customerGroupManager.selectCustomerGroupByCustomerType(customerType); + + // Then + assertEquals(customerType, actual.getCustomerType()); + } + + @DisplayName("[SELECT] 고객 유형이 주어지지 않은 경우 - Null") + @Test + void givenNothing_whenSelectCustomerGroup_thenReturnsSelectedCustomerGroup() { + // Given + + // When & Then + assertNull(customerGroupManager.selectCustomerGroupByCustomerType(null)); + } + + @DisplayName("[SELECT] 모든 고객 그룹 조회") + @ParameterizedTest(name = "고객 유형 (CustomerType): {0}") + @EnumSource(CustomerType.class) + void givenNothing_whenSelectAllCustomerGroup_thenReturnsAllCustomerGroupArray( + CustomerType customerType) { + // Given + + // When + CustomerGroup[] actual = customerGroupManager.selectAllCustomerGroup(); + + // Then + assertTrue(Arrays.stream(actual).anyMatch(group -> group.getCustomerType() == customerType)); + } +} diff --git a/src/test/java/me/smartstore/core/service/CustomerGroupServiceTest.java b/src/test/java/me/smartstore/core/service/CustomerGroupServiceTest.java new file mode 100644 index 00000000..85ce441e --- /dev/null +++ b/src/test/java/me/smartstore/core/service/CustomerGroupServiceTest.java @@ -0,0 +1,83 @@ +package me.smartstore.core.service; + +import static me.smartstore.exceptions.StoreErrorCode.NO_MATCHING_GROUP; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; + +import java.util.Arrays; +import me.smartstore.core.domain.CustomerGroup; +import me.smartstore.core.domain.CustomerGroupDTO; +import me.smartstore.core.domain.Parameter; +import me.smartstore.enums.CustomerType; +import me.smartstore.exceptions.StoreException; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class CustomerGroupServiceTest { + private final CustomerGroupService customerGroupService = CustomerGroupService.getInstance(); + + @DisplayName("[setGroupParameter] 그룹 DTO, 파라미터 전달하면 파라미터 업데이트 후 저장하고 업데이트 된 DTO 반환하고 고객 재분류") + @Test + void givenCustomerGroupDTOAndParameter_whenSetGroupParameter_thenSavesAndReturnsUpdatedDTO() { + // Given + CustomerGroupDTO beforeGroupDTO = + CustomerGroupDTO.of(CustomerType.GENERAL, new Parameter(123, 123456)); + Parameter updateParameter = new Parameter(987, 987654); + + // When + CustomerGroupDTO afterGroupDTO = + customerGroupService.setGroupParameter(beforeGroupDTO, updateParameter); + + // Then + assertEquals(afterGroupDTO.customerType(), beforeGroupDTO.customerType()); + assertEquals(afterGroupDTO.parameter().getMinSpentTime(), 987); + assertEquals(afterGroupDTO.parameter().getMinPayAmount(), 987654); + } + + @DisplayName("[find] 고객 유형을 전달하면 일치하는 그룹 DTO 를 반환") + @Test + void givenCustomerType_whenFind_thenReturnsCustomerGroupDTO() { + // Given + CustomerType customerType = CustomerType.GENERAL; + CustomerGroup customerGroup = new CustomerGroup(customerType, any()); + CustomerGroupDTO customerGroupDTO = CustomerGroupDTO.fromEntity(customerGroup); + + // When + CustomerGroupDTO actual = customerGroupService.find(customerType); + + // Then + assertEquals(customerGroupDTO.customerType(), actual.customerType()); + assertEquals(customerGroupDTO.parameter(), actual.parameter()); + } + + @DisplayName("[find] 고객 유형을 전달하지 않는 경우 예외 발생") + @Test + void givenNothing_whenFind_thenOccursStoreException() { + // Given + + // When & Then + StoreException exception = + assertThrows(StoreException.class, () -> customerGroupService.find(null)); + assertEquals(NO_MATCHING_GROUP.getMessage(), exception.getMessage()); + } + + @DisplayName("[findAll] 모든 고객 그룹 요청시 고객 그룹 DTO 를 배열로 반환") + @Test + void givenCustomerTypeAndParameter_thenSetGroupDTOParameter() { + // Given + CustomerGroup[] customerGroups = + Arrays.stream(CustomerType.values()) + .map(type -> new CustomerGroup(type, null)) + .toArray(CustomerGroup[]::new); + CustomerGroupDTO[] customerGroupDTOs = + Arrays.stream(customerGroups) + .map(CustomerGroupDTO::fromEntity) + .toArray(CustomerGroupDTO[]::new); + + // When + CustomerGroupDTO[] actual = customerGroupService.findAll(); + + // Then + assertArrayEquals(customerGroupDTOs, actual); + } +}