diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..7fe150859 --- /dev/null +++ b/.gitignore @@ -0,0 +1,199 @@ +# Default ignored files +/shelf/ +/.idea/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml + +# Created by https://www.toptal.com/developers/gitignore/api/gradle,java,macos +# Edit at https://www.toptal.com/developers/gitignore?templates=gradle,java,macos + +### 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 +.idea +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/gradle,java,macos +======== +\# Default ignored files +/shelf/ +/.idea/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml + +# Created by https://www.toptal.com/developers/gitignore/api/gradle,java,macos +# Edit at https://www.toptal.com/developers/gitignore?templates=gradle,java,macos + +### 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 +.idea +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/gradle,java,macos \ No newline at end of file diff --git a/README.md b/README.md index cd88cd211..ccfeda93b 100644 --- a/README.md +++ b/README.md @@ -20,3 +20,4 @@ ### 코드리뷰가 마쳤다면! 만족할 코드가 완성되었다면! Merge! - merge하면서 conflict가 날 수 있겠죠? Git/Github 특강을 다시보며 해결해봅시다. + diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..3ccc53725 --- /dev/null +++ b/build.gradle @@ -0,0 +1,38 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.2' + id 'io.spring.dependency-management' version '1.1.2' +} + +group = 'com.programmers' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' +} + +tasks.named('test') { + useJUnitPlatform() +} \ 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 000000000..249e5832f 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 000000000..ae04661ee --- /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 100755 index 000000000..a69d9cb6c --- /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 000000000..f127cfd49 --- /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 000000000..432bcc7b8 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'week' \ No newline at end of file diff --git a/src/main/java/com/programmers/week/WeekApplication.java b/src/main/java/com/programmers/week/WeekApplication.java new file mode 100644 index 000000000..a3c6bbbfb --- /dev/null +++ b/src/main/java/com/programmers/week/WeekApplication.java @@ -0,0 +1,13 @@ +package com.programmers.week; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WeekApplication { + public static void main(String[] args) { + SpringApplication.run(WeekApplication.class, args); + } + +} + diff --git a/src/main/java/com/programmers/week/base/BaseEntity.java b/src/main/java/com/programmers/week/base/BaseEntity.java new file mode 100644 index 000000000..840c6bcbf --- /dev/null +++ b/src/main/java/com/programmers/week/base/BaseEntity.java @@ -0,0 +1,23 @@ +package com.programmers.week.base; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseEntity { + + @Column(columnDefinition = "TIMESTAMP(6)") + @CreatedDate + private LocalDateTime createdAt; + + @Column(columnDefinition = "TIMESTAMP(6)") + @LastModifiedDate + private LocalDateTime lastModifiedAt; +} diff --git a/src/main/java/com/programmers/week/customer/application/CustomerService.java b/src/main/java/com/programmers/week/customer/application/CustomerService.java new file mode 100644 index 000000000..fcb340301 --- /dev/null +++ b/src/main/java/com/programmers/week/customer/application/CustomerService.java @@ -0,0 +1,56 @@ +package com.programmers.week.customer.application; + +import com.programmers.week.customer.domain.Customer; +import com.programmers.week.customer.infra.CustomerRepository; +import com.programmers.week.customer.presentation.CustomerCreateRequest; +import com.programmers.week.customer.presentation.CustomerResponse; +import com.programmers.week.customer.presentation.CustomerUpdateRequest; +import com.programmers.week.exception.Message; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +@RequiredArgsConstructor +public class CustomerService { + + private final CustomerRepository customerRepository; + + @Transactional + public Long create(CustomerCreateRequest request) { + Customer customer = new Customer( + request.firstName(), + request.lastName() + ); + Customer saved = customerRepository.save(customer); + return saved.getId(); + } + + public CustomerResponse findById(Long id) { + return customerRepository.findById(id) + .map(CustomerResponse::from) + .orElseThrow(() -> new IllegalArgumentException(Message.CUSTOMER_IS_NO_EXIST)); + } + + public Page findAll(PageRequest pageRequest) { + Page customerPage = customerRepository.findAll(pageRequest); + return customerPage.map(CustomerResponse::from); + } + + @Transactional + public Long update(Long id, CustomerUpdateRequest request) { + Customer customer = customerRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException(Message.CUSTOMER_IS_NO_EXIST)); + customer.changeName(request.firstName(), request.lastName()); + return customer.getId(); + } + + @Transactional + public void deleteById(Long id) { + customerRepository.deleteById(id); + } + +} diff --git a/src/main/java/com/programmers/week/customer/domain/Customer.java b/src/main/java/com/programmers/week/customer/domain/Customer.java new file mode 100644 index 000000000..ebdff991d --- /dev/null +++ b/src/main/java/com/programmers/week/customer/domain/Customer.java @@ -0,0 +1,64 @@ +package com.programmers.week.customer.domain; + +import com.programmers.week.exception.Message; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Objects; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Customer { + + private static final int MAX_FIRST_NAME_LENGTH = 5; + private static final int MAX_LAST_NAME_LENGTH = 2; + + @Id + @GeneratedValue + private Long id; + + @Column(length = 5, nullable = false) + private String firstName; + + @Column(length = 2, nullable = false) + private String lastName; + + public Customer(String firstName, String lastName) { + validateFirstName(firstName); + validateLastName(lastName); + this.firstName = firstName; + this.lastName = lastName; + } + + private static void validateFirstName(String firstName) { + if (Objects.isNull(firstName) || firstName.isBlank()) { + throw new IllegalArgumentException(Message.FIRSTNAME_IS_NULL); + } + if (firstName.length() > MAX_FIRST_NAME_LENGTH) { + throw new IllegalArgumentException(Message.NAME_LENGTH_IS_WRONG); + } + } + + private static void validateLastName(String lastName) { + if (Objects.isNull(lastName) || lastName.isBlank()) { + throw new IllegalArgumentException(Message.LASTNAME_IS_NULL); + } + if (lastName.length() > MAX_LAST_NAME_LENGTH) { + throw new IllegalArgumentException(Message.NAME_LENGTH_IS_WRONG); + } + } + + public void changeName(String firstName, String lastName) { + validateFirstName(firstName); + validateLastName(lastName); + this.firstName = firstName; + this.lastName = lastName; + } + +} diff --git a/src/main/java/com/programmers/week/customer/infra/CustomerRepository.java b/src/main/java/com/programmers/week/customer/infra/CustomerRepository.java new file mode 100644 index 000000000..20f383bf9 --- /dev/null +++ b/src/main/java/com/programmers/week/customer/infra/CustomerRepository.java @@ -0,0 +1,9 @@ +package com.programmers.week.customer.infra; + +import com.programmers.week.customer.domain.Customer; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends JpaRepository { +} diff --git a/src/main/java/com/programmers/week/customer/presentation/CustomerController.java b/src/main/java/com/programmers/week/customer/presentation/CustomerController.java new file mode 100644 index 000000000..d17f56316 --- /dev/null +++ b/src/main/java/com/programmers/week/customer/presentation/CustomerController.java @@ -0,0 +1,56 @@ +package com.programmers.week.customer.presentation; + +import com.programmers.week.customer.application.CustomerService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/customers") +@RequiredArgsConstructor +public class CustomerController { + + private final CustomerService customerService; + + @ResponseStatus(HttpStatus.CREATED) + @PostMapping + public Long create(@RequestBody CustomerCreateRequest request) { + return customerService.create(request); + } + + @ResponseStatus + @GetMapping("/{id}") + public CustomerResponse findById(@PathVariable Long id) { + return customerService.findById(id); + } + + @ResponseStatus + @GetMapping + public Page findAll(@RequestBody PageRequestDto request) { + PageRequest pageRequest = PageRequest.of(request.page(), request.size()); + return customerService.findAll(pageRequest); + } + + @ResponseStatus + @PatchMapping("/{id}") + public Long update(@PathVariable Long id, @RequestBody CustomerUpdateRequest request) { + return customerService.update(id, request); + } + + @ResponseStatus + @DeleteMapping("/customers/{id}") + public void delete(@PathVariable Long id) { + customerService.deleteById(id); + } + +} diff --git a/src/main/java/com/programmers/week/customer/presentation/CustomerCreateRequest.java b/src/main/java/com/programmers/week/customer/presentation/CustomerCreateRequest.java new file mode 100644 index 000000000..cbcfa6eb4 --- /dev/null +++ b/src/main/java/com/programmers/week/customer/presentation/CustomerCreateRequest.java @@ -0,0 +1,7 @@ +package com.programmers.week.customer.presentation; + +public record CustomerCreateRequest( + String firstName, + String lastName +) { +} diff --git a/src/main/java/com/programmers/week/customer/presentation/CustomerResponse.java b/src/main/java/com/programmers/week/customer/presentation/CustomerResponse.java new file mode 100644 index 000000000..2729ff6a2 --- /dev/null +++ b/src/main/java/com/programmers/week/customer/presentation/CustomerResponse.java @@ -0,0 +1,14 @@ +package com.programmers.week.customer.presentation; + +import com.programmers.week.customer.domain.Customer; + +public record CustomerResponse(Long id, String firstName, String lastName) { + public static CustomerResponse from(Customer customer) { + return new CustomerResponse( + customer.getId(), + customer.getFirstName(), + customer.getLastName() + ); + } + +} diff --git a/src/main/java/com/programmers/week/customer/presentation/CustomerUpdateRequest.java b/src/main/java/com/programmers/week/customer/presentation/CustomerUpdateRequest.java new file mode 100644 index 000000000..9e0a21032 --- /dev/null +++ b/src/main/java/com/programmers/week/customer/presentation/CustomerUpdateRequest.java @@ -0,0 +1,7 @@ +package com.programmers.week.customer.presentation; + +public record CustomerUpdateRequest( + String firstName, + String lastName +) { +} diff --git a/src/main/java/com/programmers/week/customer/presentation/PageRequestDto.java b/src/main/java/com/programmers/week/customer/presentation/PageRequestDto.java new file mode 100644 index 000000000..28c3e7ed9 --- /dev/null +++ b/src/main/java/com/programmers/week/customer/presentation/PageRequestDto.java @@ -0,0 +1,7 @@ +package com.programmers.week.customer.presentation; + +public record PageRequestDto( + int page, + int size +) { +} diff --git a/src/main/java/com/programmers/week/exception/Message.java b/src/main/java/com/programmers/week/exception/Message.java new file mode 100644 index 000000000..827a8e7a3 --- /dev/null +++ b/src/main/java/com/programmers/week/exception/Message.java @@ -0,0 +1,20 @@ +package com.programmers.week.exception; + +public class Message { + + public static final String CUSTOMER_IS_NO_EXIST = "고객이 존재하지 않습니다."; + + public static final String FIRSTNAME_IS_NULL = "이름이 비어있습니다."; + public static final String LASTNAME_IS_NULL = "성이 비어있습니다."; + public static final String CHEF_IS_NULL = "요리사가 비어있습니다."; + public static final String MEMO_IS_NULL = "메모가 비어있습니다."; + + public static final String POWER_PRICE_IS_WRONG = "범위를 벗어나는 파워를 입력하였습니다. : "; + public static final String TOTAL_PRICE_IS_WRONG = "범위를 벗어나는 가격을 입력하였습니다. : "; + public static final String TOTAL_QUANTITY_IS_WRONG = "범위를 벗어나는 수량을 입력하였습니다. : "; + public static final String NAME_LENGTH_IS_WRONG = "범위를 벗어나는 길이의 이름을 입력하였습니다. : "; + public static final String CHEF_LENGTH_IS_WRONG = "범위를 벗어나는 길이의 요리사 이름을 입력하였습니다. : "; + + public static final String INCORRECT_ORDER_STATUS = "수정할 주문 상태가 올바르지 않습니다. "; + +} diff --git a/src/main/java/com/programmers/week/item/domain/Car.java b/src/main/java/com/programmers/week/item/domain/Car.java new file mode 100644 index 000000000..fc174e3f3 --- /dev/null +++ b/src/main/java/com/programmers/week/item/domain/Car.java @@ -0,0 +1,36 @@ +package com.programmers.week.item.domain; + +import com.programmers.week.exception.Message; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@DiscriminatorValue("CAR") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Car extends Item { + + private static final long MIN_POWER = 0; + private static final long MAX_POWER = 1000000; + private long power; + + private Car(int price, int stockQuantity, long power) { + super(price, stockQuantity); + this.power = power; + } + + public static Car of(int price, int stockQuantity, long power) { + validatePower(power); + return new Car(price, stockQuantity, power); + } + + private static void validatePower(long power) { + if (power < MIN_POWER || power > MAX_POWER) { + throw new IllegalStateException(String.format(Message.POWER_PRICE_IS_WRONG + "%s", power)); + } + } + +} diff --git a/src/main/java/com/programmers/week/item/domain/Food.java b/src/main/java/com/programmers/week/item/domain/Food.java new file mode 100644 index 000000000..f883ad741 --- /dev/null +++ b/src/main/java/com/programmers/week/item/domain/Food.java @@ -0,0 +1,43 @@ +package com.programmers.week.item.domain; + +import com.programmers.week.exception.Message; +import jakarta.persistence.Column; +import jakarta.persistence.DiscriminatorValue; +import jakarta.persistence.Entity; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Objects; + +@Entity +@Getter +@DiscriminatorValue("FOOD") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Food extends Item { + + private static final int MAX_CHEF_LENGTH = 5; + + @Column(length = 5) + private String chef; + + private Food(int price, int stockQuantity, String chef) { + super(price, stockQuantity); + this.chef = chef; + } + + public static Food of(int price, int stockQuantity, String chef) { + validateFood(chef); + return new Food(price, stockQuantity, chef); + } + + private static void validateFood(String chef) { + if (Objects.isNull(chef) || chef.isBlank()) { + throw new IllegalStateException(Message.CHEF_IS_NULL); + } + if (chef.length() > MAX_CHEF_LENGTH) { + throw new IllegalArgumentException(String.format(Message.CHEF_LENGTH_IS_WRONG + "%s", chef)); + } + } + +} diff --git a/src/main/java/com/programmers/week/item/domain/Item.java b/src/main/java/com/programmers/week/item/domain/Item.java new file mode 100644 index 000000000..84ca28bd2 --- /dev/null +++ b/src/main/java/com/programmers/week/item/domain/Item.java @@ -0,0 +1,52 @@ +package com.programmers.week.item.domain; + +import com.programmers.week.base.BaseEntity; +import com.programmers.week.exception.Message; +import jakarta.persistence.DiscriminatorColumn; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Inheritance; +import jakarta.persistence.InheritanceType; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public abstract class Item extends BaseEntity { + + private static final int MIN_PRICE = 0; + private static final int MIN_STOCK_QUANTITY = 0; + private static final int MAX_STOCK_QUANTITY = 50; + + @Id + @GeneratedValue + private Long id; + + private int price; + private int stockQuantity; + + protected Item(int price, int stockQuantity) { + validatePrice(price); + validateStockQuantity(stockQuantity); + this.price = price; + this.stockQuantity = stockQuantity; + } + + private static void validatePrice(int price) { + if (price < MIN_PRICE) { + throw new IllegalArgumentException(String.format(Message.TOTAL_PRICE_IS_WRONG + "%s", price)); + } + } + + private static void validateStockQuantity(int stockQuantity) { + if (stockQuantity < MIN_STOCK_QUANTITY || stockQuantity > MAX_STOCK_QUANTITY) { + throw new IllegalArgumentException(String.format(Message.TOTAL_QUANTITY_IS_WRONG + "%s", stockQuantity)); + } + } + +} diff --git a/src/main/java/com/programmers/week/order/domain/Order.java b/src/main/java/com/programmers/week/order/domain/Order.java new file mode 100644 index 000000000..e7c980e3b --- /dev/null +++ b/src/main/java/com/programmers/week/order/domain/Order.java @@ -0,0 +1,59 @@ +package com.programmers.week.order.domain; + +import com.programmers.week.base.BaseEntity; +import com.programmers.week.exception.Message; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.Objects; + +@Entity +@Getter +@Table(name = "orders") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Order extends BaseEntity { + @Id + @GeneratedValue + private Long id; + + @Enumerated(EnumType.STRING) + private OrderStatus orderStatus; + + @Lob + private String memo; + + public Order(OrderStatus orderStatus, String memo) { + validateOrderStatus(orderStatus); + validateMemo(memo); + this.orderStatus = orderStatus; + this.memo = memo; + } + + private static void validateOrderStatus(OrderStatus orderStatus) { + if (Objects.isNull(orderStatus)) { + throw new IllegalArgumentException(Message.INCORRECT_ORDER_STATUS); + } + } + + private static void validateMemo(String memo) { + if (Objects.isNull(memo)) { + throw new IllegalArgumentException(Message.MEMO_IS_NULL); + } + } + + public void changeOrder(OrderStatus orderStatus, String memo) { + validateOrderStatus(orderStatus); + validateMemo(memo); + this.orderStatus = orderStatus; + this.memo = memo; + } + +} diff --git a/src/main/java/com/programmers/week/order/domain/OrderStatus.java b/src/main/java/com/programmers/week/order/domain/OrderStatus.java new file mode 100644 index 000000000..72d6c8cf3 --- /dev/null +++ b/src/main/java/com/programmers/week/order/domain/OrderStatus.java @@ -0,0 +1,7 @@ +package com.programmers.week.order.domain; + +public enum OrderStatus { + CANCELLED, + SUCCESS, + ; +} diff --git a/src/main/java/com/programmers/week/orderItem/domain/OrderItem.java b/src/main/java/com/programmers/week/orderItem/domain/OrderItem.java new file mode 100644 index 000000000..c9c424fb2 --- /dev/null +++ b/src/main/java/com/programmers/week/orderItem/domain/OrderItem.java @@ -0,0 +1,34 @@ +package com.programmers.week.orderItem.domain; + +import com.programmers.week.base.BaseEntity; +import com.programmers.week.item.domain.Item; +import com.programmers.week.order.domain.Order; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +public class OrderItem extends BaseEntity { + + @Id + @GeneratedValue + private Long id; + + @ManyToOne + @JoinColumn(name = "order_id") + private Order order; + + @ManyToOne + @JoinColumn(name = "item_id") + private Item item; + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 000000000..c95a8c828 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,28 @@ +spring: + datasource: + driver-class-name: org.h2.Driver + url: jdbc:h2:tcp://localhost/~/orderItems + username: sa + password: + + jpa: + open-in-view: false + hibernate: + ddl-auto: create + properties: + hibernate: + format_sql: true + show-sql: true + + h2: + console: + enabled: true + path: /test + +server: + servlet: + encoding: + charset: UTF-8 + enabled: true + force: true + port: 8888 diff --git a/src/test/java/com/programmers/week/customer/application/CustomerServiceTest.java b/src/test/java/com/programmers/week/customer/application/CustomerServiceTest.java new file mode 100644 index 000000000..094aca856 --- /dev/null +++ b/src/test/java/com/programmers/week/customer/application/CustomerServiceTest.java @@ -0,0 +1,91 @@ +package com.programmers.week.customer.application; + +import com.programmers.week.customer.domain.Customer; +import com.programmers.week.customer.infra.CustomerRepository; +import com.programmers.week.customer.presentation.CustomerResponse; +import com.programmers.week.customer.presentation.CustomerUpdateRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) +public class CustomerServiceTest { + + @Autowired + private CustomerService customerService; + + @Autowired + private CustomerRepository customerRepository; + + @BeforeEach + void setUp() { + customerRepository.deleteAllInBatch(); + } + + @DisplayName("존재하는 고객 아이디와 올바른 이름을 입력할 경우 고객을 수정할 수 있다.") + @ParameterizedTest + @CsvSource(value = {"영경|나|은지|박", "상민|박|명한|유", "건희|원|범준|고"}, delimiter = '|') + void updateCustomerTest(String firstName, String lastName, String newFirstName, String newLastName) { + Customer customer = new Customer(firstName, lastName); + Customer savedCustomer = customerRepository.save(customer); + Long id = savedCustomer.getId(); + + CustomerUpdateRequest updateRequest = new CustomerUpdateRequest(newFirstName, newLastName); + customerService.update(id, updateRequest); + + Customer findCustomer = customerRepository.findById(id).get(); + assertAll( + () -> assertThat(newFirstName).isEqualTo(findCustomer.getFirstName()), + () -> assertThat(newLastName).isEqualTo(findCustomer.getLastName()) + ); + } + + @DisplayName("존재하는 고객 아이디를 입력할 경우 고객을 조회할 수 있다.") + @ParameterizedTest + @CsvSource(value = {"영경|나", "상민|박", "건희|원"}, delimiter = '|') + void findCustomerTest(String firstName, String lastName) { + Customer customer = new Customer(firstName, lastName); + Customer savedCustomer = customerRepository.save(customer); + Long id = savedCustomer.getId(); + + CustomerResponse findCustomer = customerService.findById(id); + + assertAll( + () -> assertThat(findCustomer.firstName()).isEqualTo(firstName), + () -> assertThat(findCustomer.lastName()).isEqualTo(lastName) + ); + } + + @DisplayName("존재하는 고객 아이디를 입력할 경우 고객을 삭제할 수 있다.") + @ParameterizedTest + @CsvSource(value = {"영경|나", "상민|박", "건희|원"}, delimiter = '|') + void deleteCustomerTest(String firstName, String lastName) { + Customer customer = new Customer(firstName, lastName); + Customer savedCustomer = customerRepository.save(customer); + Long id = savedCustomer.getId(); + + customerService.deleteById(id); + + Optional findUser = customerRepository.findById(id); + assertFalse(findUser.isPresent()); + } + + @DisplayName("존재하지 않는 고객을 수정할 수 없다.") + @ParameterizedTest + @CsvSource(value = {"영경|나", "상민|박", "건희|원"}, delimiter = '|') + void updateCustomerFailTest(String newFirstName, String newLastName) { + assertThatThrownBy(() -> customerService.update(1029384756L, new CustomerUpdateRequest(newFirstName, newLastName))) + .isInstanceOf(IllegalArgumentException.class); + } + +} diff --git a/src/test/java/com/programmers/week/customer/domain/CustomerTest.java b/src/test/java/com/programmers/week/customer/domain/CustomerTest.java new file mode 100644 index 000000000..bff2a9ffc --- /dev/null +++ b/src/test/java/com/programmers/week/customer/domain/CustomerTest.java @@ -0,0 +1,33 @@ +package com.programmers.week.customer.domain; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertAll; + +public class CustomerTest { + + @ParameterizedTest + @CsvSource(value = {"영경|나|은지|박", "상민|박|명한|유", "건희|원|범준|고"}, delimiter = '|') + void update_Customer_Name_Success(String firstName, String lastName, String newFirstName, String newLastName) { + Customer customer = new Customer(firstName, lastName); + customer.changeName(newFirstName, newLastName); + + assertAll( + () -> assertThat(customer.getFirstName()).isEqualTo(newFirstName), + () -> assertThat(customer.getLastName()).isEqualTo(newLastName) + ); + } + + @ParameterizedTest + @CsvSource(value = {"영경|나|은지|박박박", "상민|박|명명명한한한|유", "건희|원|범준범준범준|고고고"}, delimiter = '|') + void update_Customer_Name_Fail(String firstName, String lastName, String newFirstName, String newLastName) { + Customer customer = new Customer(firstName, lastName); + + assertThatThrownBy(() -> customer.changeName(newFirstName, newLastName)) + .isInstanceOf(IllegalArgumentException.class); + } + +} diff --git a/src/test/java/com/programmers/week/order/OrderTest.java b/src/test/java/com/programmers/week/order/OrderTest.java new file mode 100644 index 000000000..d3f23ae4d --- /dev/null +++ b/src/test/java/com/programmers/week/order/OrderTest.java @@ -0,0 +1,28 @@ +package com.programmers.week.order; + +import com.programmers.week.order.domain.Order; +import com.programmers.week.order.domain.OrderStatus; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertAll; + +public class OrderTest { + + @DisplayName("올바른 주문 상태와 메모를 입력하여 수정할 수 있다.") + @ParameterizedTest + @CsvSource(value = {"SUCCESS|메모메모|CANCELLED|수정된메모메모", "CANCELLED|메모입니다|SUCCESS|수정된메모입니다"}, delimiter = '|') + void changeOrderTest(OrderStatus orderStatus, String memo, OrderStatus newOrderStatus, String newMemo) { + Order order = new Order(orderStatus, memo); + order.changeOrder(newOrderStatus, newMemo); + + assertAll( + () -> assertThat(order.getOrderStatus()).isEqualTo(newOrderStatus), + () -> assertThat(order.getMemo()).isEqualTo(newMemo) + ); + + } + +} diff --git a/src/test/java/com/programmers/week/orderItem/OrderItemTest.java b/src/test/java/com/programmers/week/orderItem/OrderItemTest.java new file mode 100644 index 000000000..4ae7466c9 --- /dev/null +++ b/src/test/java/com/programmers/week/orderItem/OrderItemTest.java @@ -0,0 +1,28 @@ +package com.programmers.week.orderItem; + +import com.programmers.week.item.domain.Car; +import com.programmers.week.order.domain.Order; +import com.programmers.week.order.domain.OrderStatus; +import com.programmers.week.orderItem.domain.OrderItem; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertAll; + +public class OrderItemTest { + + @Test + void orderItemCreateTest() { + Order order = new Order(OrderStatus.SUCCESS, "메모메모메모"); + Car car = Car.of(1000, 10, 2000); + OrderItem orderItem = new OrderItem(1L, order, car); + + assertAll( + () -> assertThat(orderItem.getItem().getPrice()).isEqualTo(1000), + () -> assertThat(orderItem.getItem().getStockQuantity()).isEqualTo(10), + () -> assertThat(orderItem.getOrder().getOrderStatus()).isEqualTo(OrderStatus.SUCCESS), + () -> assertThat(orderItem.getOrder().getMemo()).isEqualTo("메모메모메모") + ); + } + +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml new file mode 100644 index 000000000..260234b70 --- /dev/null +++ b/src/test/resources/application.yml @@ -0,0 +1,9 @@ +spring: + jpa: + open-in-view: false + hibernate: + ddl-auto: create + properties: + hibernate: + format_sql: true + show_sql: true \ No newline at end of file